A destructor is a special method which is somewhat similar to Java's finalizer method. [7] Traditionally, in C++ codes, clean-up code is placed in the destructor. The destructor for an instance is called automatically during garbage collection, when the instance is destroyed . You usually release resources not managed by the .NET runtime in the destructor (such as file or database connections).
A destructor must have the same name and case as the class it is a member of. Destructors are declared with a tilde: ~<class_name>() { // codes } Here is an example of destructor usage. 1: using System; 2: 3: public class Test{ 4: public static void Main(){ 5: Test t1 = new Test(); 6: } 7: 8: // instance constructor 9: public Test(){ 10: Console.WriteLine("running default constructor"); 11: } 12: 13: // destructor 14: ~Test(){ 15 : Console.WriteLine("running destructor"); 16 : } 17 : } Output: c:\expt>test running default constructor running destructor Before the program ends, the destructor of the Test object is invoked before it is garbage collected. Additional notes
|