Tutorialsteacher

Follow Us

C# Class and Objects

A class is like a blueprint of a specific object that has certain attributes and features. For example, a car should have some attributes such as four wheels, two or more doors, steering, a windshield, etc. It should also have some functionalities like start, stop, run, move, etc. Now, any object that has these attributes and functionalities is a car. Here, the car is a class that defines some specific attributes and functionalities. Each individual car is an object of the car class. You can say that the car you are having is an object of the car class.

Likewise, in object-oriented programming, a class defines some properties, fields, events, methods, etc. A class defines the kinds of data and the functionality their objects will have.

Define a Class

In C#, a class can be defined by using the class keyword. Let's define a class named 'Student'.

Example: Define a Class
class Student
{
    
}

A class can contain one or more constructors, fields, methods, properties, delegates, and events. They are called class members. A class and its members can have access modifiers such as public, private, protected, and internal, to restrict access from other parts of the program.

Let's add different members to the Student class.

Field

A class can have one or more fields. It is a class-level variable that holds a value. Generally, field members should have a private access modifier used with property.

Example: Field
class Student
{
    public int id;

}

Property

A property encapsulates a private field using setter and getter to assign and retrieve underlying field value.

Example: Property
class Student
{
    private int id;

    public int StudentId
    {
        get { return id; }
        set { id = value; }
    }
}

In the above example, the id is a private field that cannot be accessed directly. It will only be accessed using the StudentId property. The get returns the value of the underlying field and set assigns the value to the underlying field id.

You can also apply some additional logic in get and set, as in the below example.

Example: Property in C#
private int id;

public int StudentId
{
    get { return id; }

    set {
        if (value > 0)
            id = value;
    }
}

Auto-implemented Property

From C# 3.0 onwards, property declaration has been made easy if you don't want to apply some logic in getter or setter. Using auto-implemented property, you don't need to declare an underlying private field. C# compiler will automatically create it in IL code.

Example: Auto-implemented Property
class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In the above example, backing private field for the FirstName and LastName will be created internally by the compiler. This speed up the development time and code readability.

Method

A method can contain one or more statements to be executed as a single unit. A method may or may not return a value. A method can have one or more input parameters.

Syntax
[access-modifier] return-type MethodName(type parameterName1, type parameterName2,...)
{
    

}

The following defines the Sum method that returns the sum of two numbers.

Example: C# Method
public int Sum(int num1, int num2)
{
    var total = num1 + num2;
    
    return total;
}

The following method doesn't return anything and doesn't have any parameters. The return type is void.

Example: C# Method
public void Greet()
{
    Console.Write("Hello World!");
}

The following defines the GetFullName() method in the Student class.

Example: Method
class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string GetFullName()
    {
        return FirstName + " " + LastName;
    }
}

Constructor

A constructor is a special type of method which will be called automatically when you create an instance of a class. A constructor is defined by using an access modifier and class name <access-modifier> <class-name>().

Example: Constructor
class Student
{
    public Student()
    {
        //constructor
    }
}
  • A constructor name must be the same as a class name.
  • A constructor can be public, private, or protected.
  • The constructor cannot return any value so cannot have a return type.
  • A class can have multiple constructors with different parameters but can only have one parameterless constructor.
  • If no constructor is defined, the C# compiler would create it internally.

Objects of a Class

You can create one or more objects of a class. Each object can have different values of properties and field but methods and events behaves the same.

In C#, an object of a class can be created using the new keyword and assign that object to a variable of a class type. For example, the following creates an object of the Student class and assign it to a variable of the Student type.

Example: Create an Object of a Class
Student mystudent = new Student();

You can now access public members of a class using the object.MemberName notation.

Example: Access Members of a Class
Student mystudent = new Student();
mystudent.FirstName = "Steve";
mystudent.LastName = "Jobs";

mystudent.GetFullName();

You can create multiple objects of a class with different values of properties and fields.

Example: Create Multiple Objects of a Class
Student mystudent1 = new Student();
mystudent1.FirstName = "Steve";
mystudent1.LastName = "Jobs";

Student mystudent2 = new Student();
mystudent2.FirstName = "Bill";
mystudent2.LastName = "Gates";