C# Class, Object and Method

Updated on     Kisan Patel

A class is an abstract model used to define a new data types. A class may contain any combination of encapsulated data like properties, member variables, methods.

In the C#, you define a class by using the class keyword. Following the class keyword the class name and curly brackets as shown below.

class MyClass {

// properties, variables, methods

}

Once a class is defined, you can add class members to it.

Class members can include constants, fields, methods, properties etc.


Objects

An object is the instance of the related class. An object is created using the keyword ‘new’ and is referenced by an identifier called a “reference”.

The syntax for creating object.

MyClass myObjReference = new MyClass();

In the line above, we make an object of type MyClass which is referenced by an identifier myObjReference.


Methods

Methods are the operations performed on the data. A method may take some input values through its parameters and may return a values of a particular data type.

The Syntax of the method is –

<return data type> <name of the method>(<parameters>) {

  //body of the method

}

For Example,

int Sum(int num1, int num2){

   return num1 + num2;

}

In above example, we have defined method and name it to Sum which takes two parameters of integer type and return a value of type int using the keyword return.

If a method does not return anything, its return type would be void.

For Example,

void Sum(int num1, int num2) {

	Console.WriteLine("The sum of num1 and num2 is {0}", num1 + num2);

}

Accessing the members of a class

The members of a class like fields, methods are accessed using dot operator against the reference of the object.

For Example,

MyClass myObj = new MyClass();
myObj.name = "Kisan";
myObj.Sum(2, 4);
For example, there is a class String in the System namespace of .Net Framework class library. This class contains an array of characters(data) and provide different method that can be applied to its data like ToLowerCase(), Substring(), Trim() and properties like Length.
using System;

namespace ConsoleApp
{
    class Student
    {
        string name;
        int markOfMath;
        int marksOfPhysics;
        int Totalmarks;

        int Sum()
        {
            return markOfMath + marksOfPhysics;
        }

        static void Main(string[] args)
        {
            Student obj = new Student();
            obj.name = "Neel";
            obj.markOfMath = 70;
            obj.marksOfPhysics = 80;
            obj.Totalmarks = obj.Sum();


            Console.WriteLine("Name of the Student : " + obj.name);
            Console.WriteLine("Total Marks : " + obj.Totalmarks);
        }
        
    }
}

The output of the above program…

csharp-class-objects-methods-demo


C#

Leave a Reply