What is destructor and how to use destructor in C# code
Description
A destructor method called just prior to an object's final destruction by the garbage collector. A destructor can be used to ensure that an object terminates cleanly.
Syntax
Destructors have this general form:
class ClassName{/*from w w w . ja v a 2s . co m*/
~ClassName() {
// destruction code
}
}
ClassName
is the name of the class.
Example
Example for C# Destructor
using System;//from w w w . ja v a2 s .c o m
class MyClass
{
~MyClass()
{
Console.WriteLine("Finalizing");
}
}
class MainClass
{
static void Main(string[] args)
{
MyClass fc = new MyClass();
Console.WriteLine("Exiting main");
}
}
The code above generates the following result.
Example 2
Destructor calling sequence
using System; /*from w w w. j a va 2s .c o m*/
class Destruct {
public int x;
public Destruct(int i) {
x = i;
}
// called when object is recycled
~Destruct() {
Console.WriteLine("Destructing " + x);
}
}
class DestructDemo {
public static void Main() {
Destruct ob = new Destruct(0);
for(int i=1; i < 100; i++){
Destruct o = new Destruct(i);
}
Console.WriteLine("Done");
}
}
The code above generates the following result.
Example 3
Update static field in the deconstructor
public class MyClass
{/*from w w w . ja v a2 s . c o m*/
private static int numberOfMyClass = 0;
public MyClass()
{
System.Console.WriteLine("Creating a MyClass object");
numberOfMyClass++;
}
~MyClass()
{
System.Console.WriteLine("Destroying a MyClass object");
numberOfMyClass--; // decrement numberOfMyClass
}
public static int GetNumberOfMyClass()
{
return numberOfMyClass;
}
}
class MainClass
{
public static void Main()
{
System.Console.WriteLine("MyClass.GetNumberOfMyClass() = " + MyClass.GetNumberOfMyClass());
MyClass myMyClass = new MyClass();
System.Console.WriteLine("MyClass.GetNumberOfMyClass() = " + MyClass.GetNumberOfMyClass());
MyClass myMyClass2 = new MyClass();
System.Console.WriteLine("MyClass.GetNumberOfMyClass() = " + MyClass.GetNumberOfMyClass());
}
}
The code above generates the following result.
Example 4
In the following example a base class is defined first. And the base class has a destructor. Then a derived class is created and extending the base class. In the derived class there is also a destructor. From the result we can see that the child destructor calls the base destructor automatically.
using System;//from w w w .ja v a2 s . c o m
public class Base
{
~Base()
{
Console.WriteLine( "Base.~Base()" );
}
}
public class Derived : Base
{
~Derived()
{
Console.WriteLine( "Derived.~Derived()" );
}
}
public class MainClass
{
static void Main()
{
Derived derived = new Derived();
}
}
The code above generates the following result.