C# Constructors and Destructors

Constructors
A constructor is a special class member that is executed when a new object is created. The constructor’s job is to initialize all of the public and private state of the new object and to perform any other tasks that the programmer requires before the object is used.
In this article, we will create a new class to represent a triangular shape. This class will define three properties: the triangle’s height, base-length and area. To begin, create a new console application and add a class named “Triangle”. Copy and paste the following code into the class to create the three properties that are required.

public class Triangle
{
private int _height;
private int _baseLength;
public int Height
{
get
{
return _height;
}
set
{
if (value < 1 || value > 100)
throw new OverflowException();
_height = value;
}
}
public int BaseLength
{
get
{
return _baseLength;
}
set
{
if (value < 1 || value > 100)
throw new OverflowException();
_baseLength = value;
}
}
public double Area
{
get
{
return _height * _baseLength * 0.5;
}
}
}

The Default Constructor
Every class includes a default constructor that is applied if no other constructor is explicitly declared by the developer. This constructor causes all of the value type properties and variables to be set to zero and all reference types to be set to null. If these are invalid values for an object, as in the Triangle class above, the default constructor will always create an object that is invalid. In this case, the default constructor should be replaced.
Replacing the Default Constructor
The syntax to add a new constructor to a class is similar to that of adding a method. However, the constructor has the same name as the class and does not include a return type. The declaration for the Triangle’s new constructor is therefore simply:

public Triangle()

To ensure that all triangles will have a height and base-length within the valid range, we will make the class constructor set both of these properties to one unit for all new Triangle objects. This is achieved by simply setting the underlying private variables in the constructor’s code block. Add the following code within the class code block to add the constructor.

public Triangle()
{
Console.WriteLine("Triangle constructor executed");
_height = _baseLength = 1;
}

NB: The Console.WriteLine command is added to show that the constructor has been executed in the examples. This would generally not be added to a real class definition.
Executing the Constructor
The newly added constructor replaces the default constructor and is executed automatically when a new Triangle is instantiated. This can be tested by adding some code to the console application’s Main method. Add the following code and execute the program to test the results and to see that the height and base-length are set correctly.

static void Main(string[] args)
{
Triangle triangle = new Triangle();
Console.WriteLine("Height:t{0}", triangle.Height);
Console.WriteLine("Base:t{0}", triangle.BaseLength);
Console.WriteLine("Area:t{0}", triangle.Area);
}

/* OUTPUT
Triangle constructor executed
Height: 1
Base: 1
Area: 0.5
*/

Parametrized Constructors
The previous example shows the addition of a new constructor to a class. However, this constructor is very limiting as it includes no parameters to control the initialization process. To enhance the constructor, we can add parameters in the same way as they would be added to any other method. The following constructor adds two parameters so that the height and base-length of the triangle can be specified during instantiation. It set the properties of the class rather than directly setting the private variables to re-use the validation that they provide. Update the constructor with this version.

public Triangle(int height, int baseLength)
{
Console.WriteLine("Triangle constructor executed");
this.Height = height;
this.BaseLength = baseLength;
}

If you try to build or execute the console application you will now receive a compiler error indicating that no constructor is available that accepts zero arguments. This is because the Main method is still trying to use the default constructor. As this has been replaced, the Main method must be adjusted to use the new, parametrized version as follows:

static void Main(string[] args)
{
Triangle triangle = new Triangle(5,8);
Console.WriteLine("Height:t{0}", triangle.Height);
Console.WriteLine("Base:t{0}", triangle.BaseLength);
Console.WriteLine("Area:t{0}", triangle.Area);
}

/* OUTPUT
Triangle constructor executed
Height: 5
Base: 8
Area: 20
*/

Destructors
A destructor is a special member that can be added to a class. It is called automatically when an object is no longer required and is being removed from memory. The destructor can be useful because it can ensure that all objects of a particular class terminate cleanly. For example, if a class maintains a database connection, the destructor can be used to ensure that any database transaction is rolled back if it has not been committed and that the database connection is closed when the object is cleaned up.
Destructors are sometimes known as finalizes. In other .NET languages, the object class’ Finalize method can be overridden to provide the clean-up code. In C#, this is not permitted so the destructor syntax must be used. This forces the calling of the finalize of the base class of the object too, by implicitly converting the destructor statements into the Finalize code below:

protected override void Finalize()
{
try
{
// Destructor code
}
finally
{
base.Finalize();
}
}

Creating a Destructor
The syntax to create a destructor is very simple. The class name is prefixed with a tilde character (~). No parameters are permitted as the destructor cannot be called manually. To add a destructor to the Triangle class, add the following code:

~Triangle()
{
Console.WriteLine("Triangle destructor executed");
}

NB: The destructor outputs a message only as there is no clean up required for Triangle objects.
Executing the Destructor
The destructor is executed automatically when the object is being removed from memory. This can be demonstrated by running the console application. The output should be as follows:

Triangle constructor executed
Height: 5
Base: 8
Area: 20
Triangle destructor executed

Tagged , . Bookmark the permalink.

Leave a Reply