Search This Blog

Friday, 20 July 2012

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

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..");
}
Once the object is collected by the garbage collector, this method is called.


PREVIOUS CHAPTER
 NEXT CHAPTER

No comments:

Post a Comment