Use destructor and implement IDisposable : destructor « Class « C# / CSharp Tutorial






using System;
public class MyClass : IDisposable
{
  ~MyClass()
  {
    Console.WriteLine("In destructor");
  }
  
  public void Dispose()
  {
    Console.WriteLine("In Dispose()");
    GC.SuppressFinalize(this);
  }
}

public class MainClass
{
  public static void Main(string[] args)
  {    
    MyClass c1, c2, c3, c4;

    c1 = new MyClass();
    c2 = new MyClass();
    c3 = new MyClass();
    c4 = new MyClass();
    
    Console.WriteLine("\n***** Disposing c1 and c3 *****");
    c1.Dispose();
    c3.Dispose();
  }
}
***** Disposing c1 and c3 *****
In Dispose()
In Dispose()
In destructor
In destructor








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