Tuesday, March 16, 2010

Destructors

Destructors are used to destruct objects. A destructor is declared as shown in this example:
~MyClass()
{
    //Destruction statements.
}
The destructor of a class uses the same name as the class but is preceded with the tilde (~) character. We cannot, however, call a destructor as it is called automatically when the object finished its work and goes out of scope. In case of inheritance, the destruction starts with the children and goes up in the inheritance tree.
The following example shows how destructors are called to destruct objects in the order of their position in the inheritance hierarchy.
Example: -
//Example 5-13.cs
//Destructor example
using System;
class Parent    //parents
{
    ~Parent()
    {
        Console.WriteLine(“Calling the Parent destructor.”);
    }
}
class Kid: Parent //kids
{
    ~Kid()
    {
        Console.WriteLine(“Calling the Kid destructor.”);
    }
}
class GrandKid: Kid // grandkids
{
    ~GrandKid()
    {
        Console.WriteLine(“Calling the Grandkid destructor.”);
    }
}
public class MyClass
{
    public static void Main()
    {
        GrandKid myObject = new GrandKid();
    }
}
Notice in this example that the grandkid was destructed first, then the kid, and finally the parent.
In C# we don’t need to use them because the garbage collector does that task for our automatically when the objects finish their work and are no longer in use.
In C#, we can still use destructors to clear unmanaged resources such as files and network connections.
Note: We can force the garbage collector to start the cleaning process by using the .NET GC.Collect method, but this is not recommended as it might cause undesirable results.

No comments:

Post a Comment