7.5 Destructors


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).

[7] Destructors came from C++. In C++ classes, destructors are called when the object is manually deleted using the C++ delete keyword. That's where you would recursively delete other objects created and referenced exclusively by the current object. Poor destructor programming in C++ leads to memory-leaky applications. Unlike C++, C# (and Java) has the luxury of automatic memory management. Destructors are no longer as important since any lingering objects which cannot be referenced will be cleaned up by the garbage collector.

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

  • Destructors cannot have parameters and access modifiers. And since destructors cannot have parameters, it follows that each class can have only up to one destructor.

  • They cannot be called explicitly. Since garbage collection is non-deterministic , it cannot be predicted when the destructor of an instance will run.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net