Constructors and Destructors in C#

 

Constructors:

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.


Let's consider this example, 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 how.


public Car()

{

}


public Car(string color)

{

         this.color = color;

}

A constructor can call another constructor, which will be helpful in different situations and below snippet will give you an idea.

 

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  as shown below.

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 single parameter.

 

Destructors:
Since C# is garbage collected, meaing 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..");

}