TOC

The community is working on translating this tutorial into Punjabi, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Classes:

Constructors and destructors

Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it. A normal method is defined like this:

public string Describe()

A constructor can be defined like this:

public Car()

In our example for this chapter, we have a Car class, with a constructor which takes a string as argument. Of course, a constructor can be overloaded as well, meaning we can have several constructors, with the same name, but different parameters. Here is an example:

public Car()
{

}

public Car(string color)
{
    this.color = color;
}

A constructor can call another constructor, which can come in handy in several situations. Here is an example:

public Car()
{
    Console.WriteLine("Constructor with no parameters called!");
}

public Car(string color) : this()
{
    this.color = color;
    Console.WriteLine("Constructor with color parameter called!");
}

If you run this code, you will see that the constructor with no parameters is called first. This can be used for instantiating various objects for the class in the default constructor, which can be called from other constructors from the class. If the constructor you wish to call takes parameters, you can do that as well. Here is a simple example:

public Car(string color) : this()
{
    this.color = color;
    Console.WriteLine("Constructor with color parameter called!");
}

public Car(string param1, string param2) : this(param1)
{

}

If you call the constructor which takes 2 parameters, the first parameter will be used to invoke the constructor that takes 1 parameter.

Destructors

Since C# is garbage collected, meaning that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class:

~Car() 
{
    Console.WriteLine("Out..");
}

Once the object is collected by the garbage collector, this method is called.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!