C#: Classes (Part – 1)

‘C#’ classes are code blocks that combine data and operations those work on the data. ‘C#’ classes enables Object Oriented Programming (OOP) concepts of encapsulation and abstraction. Encapsulation means combining data and the operations apply on the data together. Abstraction means hiding the details to outer world. ‘C#’ classes are created using the class keyword. Below is the syntax to create a class in ‘C#’:

class <class-name>

Where <class-name> is the name of the class. And it is case sensitive. That means for example: “Sample” is the class name, and we can define another class “sample”. Then “Sample” and “sample” are two different classes. To avoid confusion, it is better to give unique and meaningful names to the classes. The class contains data and operations; together we can call these are members of a class. To access members of a class, we need to create instance of a class, an object. Once the class’s object is created, we can access class’s members. Lets take a simple example:

// Sample.cs
//
class Sample
{
    int id = 100;

    void Display()
    {
        System.Console.WriteLine("Hello, World! My id is: " + id);
    }

    static void Main()
    {
        Sample obj = new Sample();
        if (obj != null)
            obj.Display();
    }
}

From above code, “Sample” is the name of the class. It has one data member “id” and one member function “Display”. “Display” is the member function which will display “Hello, World!” message on the screen. We have created an instance of the class

Sample obj = new Sample();

“obj” is the “Sample” class’s object. So, we can access “Sample” class members through its object “obj”. Hence we called “Display” through “obj”. When you compile and run the program it will display the following message on screen:

Hello, World! My id is: 100

Class Initialization Data members declared in the class are initialized in different ways.

  • In the member declaration section
  • Through class Constructors
  • Initializers

From above mentioned sample code we have seen the initialization of a class member in declaration section i.e.,

int id = 100;

This is one way of initializing class members. ‘C#’ provides special methods for initialization of class members called Constructors.

  • Constructors are automatically called at the time of creating an instance of a class.
  • Constructors doesn’t have any return value. Constructors name will be same as the class name.
  • Like normal methods of a class, Constructors will take “0” or more number of arguments.
  • If none of the constructors are provided for a class, ‘C#’ automatically creates a Constructor for us. For example: if the class name is “Sample”, the constructors will looks like below:
    Sample()
    {
        id = 100;
    }
    Sample(int value)
    {
        id = value;
    }

Another way of initializing class members is through Initializers. Initializers directly access the class members at the time of creating an instance of a class. For example:

Sample obj = new Sample { id = 300 };

Here observe that “id = 300” is the Initializer. “id” is “Sample” class’s member and accessing at the time instance creation and assign it will the value “300”. Over these three ways of initialization, which one will initialize first? ‘C#’ first initializes the member in declaration section. Second, it will initialize the members in the Constructors. Then after constructing the object, Initializer will initialize the members. For example: if you initialize the member value in all these three ways, you will get the value only which is initialized through Initializers; rest of the values are simply overwritten on particular member. Cleanup Other special method ‘C#’ provides is Destructor. Class’s Destructor is used to cleanup the memory which is allocated in previous calls for class members. Class Destructor will be called at the time of deleting the object (an instance of a class). In ‘C#’, usually it is not required to cleanup the memory, because Garbage Collector will cleanup the memory for all managed code. Like Constructors, Destructors don’t have any return value. Destructors always have no arguments and the name of the Destructor is same as the name of the class. Destructors starts with “~” symbol. For example: if the class name is “Sample” then the Destructor will be:

~Sample()
    {
        // Some cleanup code goes here
    }

Lets put all together; here is the code.

class Sample
{
    int id = 100;

    /* Class constructor */
    Sample()
    {
        id = 200;
    }

    /* Argument constructor */
    Sample(int id)
    {
        this.id = id;
    }

    /* Class Method */
    void Display()
    {
        System.Console.WriteLine("Hello, World! My id is: " + id);
    }

    /* Class Destructor */
    ~Sample()
    {
        // Some cleanup code goes here
    }

    static void Main()
    {
        Sample obj1 = new Sample();
        if (obj1 != null)
            obj1.Display();

        Sample obj2 = new Sample { id = 300 };
        if (obj2 != null)
            obj2.Display();
    }
}

Observer that we have used different ways to initialize class members. We will discuss more about classes in our next articles…

..

Leave a Reply