Update static field in the deconstructor : destructor « Class « C# / CSharp Tutorial






public class MyClass
{
  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());
  }
}
MyClass.GetNumberOfMyClass() = 0
Creating a MyClass object
MyClass.GetNumberOfMyClass() = 1
Creating a MyClass object
MyClass.GetNumberOfMyClass() = 2
Destroying a MyClass object
Destroying a MyClass object








7.14.destructor
7.14.1.Destructors
7.14.2.Simple Finalize
7.14.3.Illustrates a destructor
7.14.4.Demonstrate a destructor.
7.14.5.Use destructor and implement IDisposable
7.14.6.Base destructor
7.14.7.Update static field in the deconstructor