Destructor
In this chapter you will learn:
Create destructors
DestructorA 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. Destructors have this general form:
~class-name( ) {
// destruction code
}
class-name
is the name of the class.
using System;/*from ja v a2 s .com*/
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.
Destructor calling sequence
using System; // j a va2s. co 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.
Destructor and static fields
The following code
public class MyClass
{//from j av 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.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class