Destructors and IDisposable

  • Managed Resource – The objects that are created by CLR are called as “Managed Resources”
    • These will participate in “Garbage Collection” process, which is part of .net framework.
  • Unmanaged resources :- Objects that are not created by CLR are called unmanaged resources. Example – filestream, database connection
  • Who will clear the unmanaged resources??
    1. Destructor – clears the unamanaged resources – generally at the end of application execution
      1. Special method of the class which is used to close unmanaged resources (such as database connections, file connections) that are opened during the class execution.
      2. ~className{ } 
    2. Dispose – clears the unmanaged resources after the specific task is completed. No need to wait till the end of application execution.
  • Destructor:- We close those external connections so that there is no memory leakages.
  • Destructor is public by default , we can’t change its access modifier.
  • In IL it gets converted to finalize method
  • Destructor doesn’t deallocate any memory, it just will be called by CLR (.net runtime engine) automatically just before the moment of deleting the object of the class.
  • IDisposable has an interface called Dispose method which is used to close unmanaged objects.
				
					using ConsoleApp25;

class Program
{
    static void Main(string[] args)
    {
        Play();
        Console.ReadKey();
    }

    public static void Play()
    {
        using (Cricket obj1 = new ())
        {
            obj1.Batting();
        }
            
    }
}






				
			
				
					
namespace ConsoleApp25
{
    public class Cricket :IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("Dispose method is called here");
        }

        public void Batting()
        {
            Console.WriteLine("Batting started !!");
        }
    }
}

				
			

new method called !!
Dispose method is called here

Leave a Comment