Update static field in the deconstructor : Destructor : Class C# Examples


C# Examples » Class » Destructor »

 

Update static field in the deconstructor









    
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());
    }
}
    
   
  
   



Output

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


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Class
» Destructor