Thursday, July 23, 2009

Constructors and Destructors

Constructors and Destructors are methods that are automatically called when a class is instansiated or destroied. They are provided so that the class can be initialised with the correct data, open connections and so on and also to finalise and close connections and files before the object is removed from memory.

You do not need to provide a constructor method on your classes as the compiler will automatically initialise fields to default values using a default constructor which takes no parameters. A constructor should be used when you need non-default values to be initialised. Constructors can also be overloaded to extend the functionality of the method. If you do create an overloaded constructor, the compiler will not provide a default, so if you still require a constructor with no parameters you must provide it yourself.

A constructor is declared as a public method with the same name as the class.

public class testClass
{
public int myVar;

// Default constructor
public testClass()
{
myVar = 123;
}
}

public class Program
{
static void Main()
{
testClass test = new testClass();
Console.WriteLine(testClass.myVar);
}
}

When instantiating the class with the new keyword, you can pass a parameter to the constructor, however if you do this you must create a default constructor if you need it.

public class testClass
{
int myVar;

// Default constructor
public testClass(int x)
{
myVar = x;
}
}

public class Program
{
static void Main()
{
testClass test = new testClass(10);

// The following will not work as there is no default constructor provided.
testClass test2 = new testClass();
}
}

You can also mark the constructor as private, which will have the effect of not allowing the class to be instanciated. This is useful for abstract classes where you should not create an instance.

Destructors work slightly differently in that the syntax is a shortcut to an override of the Finalize method, however all you really need to know is that they are used to finalise the class ready for removal from memory. The Garbage Collector always calls the destructor, you never call it from within your code. Since you cannot call the destructor, you cannot overload the destructor method.

~testClass()
{
// Close connections, Files etc…
}

This is interpreted by the compiler to:

protected override void Finalize()
{
try
{
// Close connections, Files etc…
}
finally
{
base.Finalize();
}
}

No comments:

Post a Comment