10 - Introduction to Classes in C#

10.1 Classes in C#

A class is a template that defines the form of an object. It specifies both the data and the code that operate on the data. C# uses the class specification to construct objects. Objects are the instance of a class.

When user creates a class, we can declare data that it contains and the code that operates on it. A class is created by the use of keyword class. The general form of a class definition that contains the instance variables and methods is as shown below:

class classname
{
//declare instance variables
access type var1;
access type var2;

//declare methods
access return_type method1(parameters)
{
//body of the method
}
}

The class keyword is preceded by the access level. Depending on the access specifiers, the objects can be accessed by the user.

Consider an example of class called as Building. The Building class consists of three instance variables as floors, area and occupants. It does not contain any methods. It is a data only class created by the user. The code for the class is as shown below:

class Building
{
    public int floors;
    public int area;
    public int occupants;
}

A class definition is the creation of new data type. In the above example, Building is the new data type. The class is only the description of the type. The actual object is not created by the class. The preceding code does not cause any object of type building to come into existence.

To create a building object, the following statement is used.

Building house = new Building();

The declaration performs two functions. First, it declares a variable called house of the class type Building. Second, the declaration creates an actual copy of the variable and assigns to house a reference to that object. The new operator is used for the creation of the object. It dynamically creates the memory for an object and returns the reference to it.

To access the variables of the class, you can use the dot (.) operator. The general form of the dot operator is as shown below:

object.member

The object is specified on the left side and the member on the right.

The code sample for the class building is as shown below:

class Building
{
    public int floors;
    public int area;
    public int occupants;
    
    public static void Main()
    {
        Building house = new Building();
        house.floors = 5;
        house.area = 10000;
        house.occupants = 50;
        Console.WriteLine(“The number of floors of the building are:”+house.floors);
        Console.WriteLine(“The area of the building is:”+house.area);
        Console.WriteLine(“The number of occupants of the building are:”+house.occupants);
        Console.Read();
    }
}

 

The output for the code is as shown below:

10.2 Types of constructors

A constructor is a type of method that is invoked directly when you create an instance or object of a class. They are responsible for object initialization and memory allocation of its class. There is always one constructor in every class. The constructor name is same as that of its containing class. 

There are two types of constructors supported by C#. They are as mentioned below:

1) Instance Constructors

2) Static Constructors

1) Instance Constructors:

When an instance of a class is created, an instance of constructor is called.  They are used to initialize the member variables of a class. The constructor does not have a return type. They can have access modifiers. 

The example to create Instance constructor is as shown below:

class Calculator
{
    static int no1, no2, total;
    Calculator()
    {
        no1 = 100;
        no2 = 200;
    }
    public void Addno()
    {
        total = no1+no2;
    }    
    public void Show()
    {
        Console.WriteLine(“The total is:{0}”, total);
    }
    public static void Main ()
    {
        Calculator c1 = new Calculator();
        c1.Addno();
        c1.Show();
        Console.Read();
    }
}

The output for the code is as shown below:

In the preceding code, there is no return type specified for the Calculator() constructor. This is because constructors do not have any return type. The no1 and no2 variables assigned with values 100 and 200 respectively.

2) Static Constructors:

Static constructors are used for the initialization of the static variables of a class. The static keyword is used for creating the variables. The values that can be shared by all the instance of the class are stored. They contain an implicit private access. 

The following code snippet demonstrates the static constructor in C#.

class Calculator
{
    static int no1;
    static Calculator()
    {
        no1 = 100;
    }
    static void IncrementData()
    {
        no1++;
    }
    public void Show()
    {
        Console.WriteLine(“The number is:{0}”, no1);
    }
    public static void Main ()
    {
        Calculator c1 = new Calculator();
        IncrementData();
        c1.Show();
        Console.Read();
    }
}

 

The output for the code is as shown below:

10.3 Constructors with Parameters

Constructors are used to initialize the variables of the program with the code values in the program itself. There may be requirement where the variables need to be initialized with the values added by the user.

The following code shows the use of the constructor with parameters.

class Calculator
{
    static int no1, no1, total;
    Calculator ( int num1, int num2 )
    {
        no1 = num1;
        no2 = num2;
    }
    public void SubNumber()
    {
        total = no1 – no2;
    }
    public void Show()
    {
        Console.WriteLine(“The difference is:{0}”, total);
    }
    public static void Main ( )
    {
        int a, b;
        Console.WriteLine(“Enter the first value”);
        a=Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(“Enter the second value”);
        b=Convert.ToInt32(Console.ReadLine());
        Calculator c1 = new Calculator();
        c1.SubNumber();
        c1.Show();
        Console.Read();
    }
}

 

The output for the following code is as shown below:

In the above code, the initialization values are passes to the member variables during the creation of object. While accepting the values from the user, Convert.ToInt32() method is used to convert the string to integer value.

10.4 Declaration of Destructors

Destructors are the special method used for releasing the instance of a class from memory. A class can have only one destructor. The memory cleaning action is performed using the destructors. The .NET framework constantly checks for the objects that are released from the memory. 

A destructor has the same name as its class but it is prefixed by ~ symbol, which is represented by a tilde. The following class demonstrates the use of destructors in C#.

class Calculator
{
    static int no1, no2, result;
    public void Multiply()
    {
        result = no1 * no2;
        Console.WriteLine(“The result is:{0}”, result);
    }
    Calculator()
    {
        no1 = 2;
        no2 = 3;
        result = 0;
        Console.WriteLine(“Constructor Invoked”);
    }    
    ~Calculator()
    {
        
         Console.WriteLine(“Destructor Invoked”);
    }
    public static void Main ( string[ ] args )
    {
        Calculator c1 = new Calculator();
        c1.Multiply();
        Console.Read();
    }
}

 

The output for the code is as shown below:

In the above code, the .NET framework automatically runs the destructor to destroy the objects in the memory and displays the message.

10.5 Life cycle of an object

The .NET framework is the managed code environment where the garbage collector disposes  the unused objects to free up memory.  The new operator creates an object, the memory is used from the managed heap. The unused objects are collected using the garbage collector.

The steps in creation of the life cycle of an object are as mentioned below:

1) The new operator allocates the memory on the managed heap

2) The memory is allocated and the objects constructor is called in the application

3) The object is used for a period of time

4) The object is destroyed when all references are explicitly set to null or out of scope

5) The objects memory is reused after some time and is available for other objects

Allocation of an object: When the new object is created, the memory is allocated with the next location on the managed heap. If there is memory available, the garbage collector does not search for the allocation space.

The garbage collector classifies all objects into three generations uses three generations to group objects by their lifetime. There types are as mentioned below:

Generation 0: They are used to collect the short lived objects are collected quickly. Objects that live a generation 0 collection are passed to generation 1.

Generation 1: They are less frequently used as compared to generation 0. Objects that have long lived are promoted from generation 0 to 1. Objects that survive a generation 1 are passed to generation 2.

Generation 2: Objects that are passed from generation 1 are the longest lived objects. They are less frequently collected.

The following code shows the life cycle of an object.

class TestCalculator
{
    TestCalculator()
    {
        Console.WriteLine(“Constructor Invoked”);
    }
    ~TestCalculator()
    {
        Console.WriteLine(“Destructor Invoked”);
    }
    public static void Main ( string [ ] args )
    {
        Console.WriteLine(“Main Block Begins”);
        TestCalculator tc = new TestCalculator();
        {
            Console.WriteLine(“Inner Block Begins”);
            TestCalculator tc1 = new TestCalculator();
            Console.WriteLine(“Inner Block Ends”);
        }
        Console.WriteLine(“Main Block Ends”);
        Console.Read();
    }
}

 

The output for the code is as shown below:

In the output, the tc object has a scope. Hence, the constructor is executed when the Main() begins. The tc1 object has a block scope. The constructor is executed after the inner block begins. The destructors are invoked when the object is garbage collector is used.

Like us on Facebook