Search:

Custom Search
_________________________________________________________________

Wednesday, August 6, 2008

Using destructors in C#

Destructors are similar to de Constructors, almost the oposite.
The destructor is used by the CLR when objects are destroyed.
All this process happens in the background so the developer does not have to preocupate about deleting
created objects. Writing a destructor is not necessary but if you are going to create one in your class,
you can only add one.
The Destructors sintaxis are very similar to the constructors.
They start with the simbole ~ and the name must be the same to the class.
Also, there are a few particulares things about destructors you should know:
-No parameters are allowed here.
-As said before, you can only write one.
-You can not call a constructor like you will normally do with a method. They are automatically used by the CLR (by the garbage collection).
-No overload or inheritances are allowed.
So let’s write a small C# class.

-Class Plane

using System;
using System.Text;

class Plane
{

public String type;
public String company;

public Plane(String t, String c){
type = t;
company = c;

Console.WriteLine("Constructor in action\n");

}

~Plane() {
type = "N/A";
company = "N/A";

Console.WriteLine("Destructor in action");
}

}

- Main

static void Main(string[] args)
{

Plane p = new Plane("AirBus", "Tam");

}

- Console

1 comment:

my blog said...

Nice article,I enjoyed reading it.



Voucher Codes