Sunday 4 January 2015

C# Constructors & Destructors

Constructors 
By default each class will have Constructor with it's class name.
Ex: If i create a class with name Car.
class Car
{
}

one Constructor will create as below..
  public Car()
        {
         
        }

If you want to change anything inside Constructor, you can change it as below..

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


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()

or

public Car()

Constructor can be overloaded as well, meaning we can have several constructors, with the same name, but different parameters.

overloaded: with the same name, but different parameters

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!");
}


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..");
}
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.