If we don’t use an IDisposable in a using block, will the Dispose method be called?

The answer is No. The Dispose method is invoked by the runtime only when the class that implements the IDisposable interface is initialized with a static block setup.

class MyClass : IDisposable 
{
  public void Dispose()
  {
     Console.WriteLine("Calling MyClass.Dispose");
  }
}

MyClass c = new MyClass();
using(MyClass uc = new MyClass()) {}

output:
Calling MyClass.Dispose  //printed only once

The answer is No. The Dispose method is invoked by the runtime only when the class that implements the IDisposable interface is initialized with a static block setup.

class MyClass : IDisposable 
{
  public void Dispose()
  {
     Console.WriteLine("Calling MyClass.Dispose");
  }
}

MyClass c = new MyClass();
using(MyClass uc = new MyClass()) {}

output:
Calling MyClass.Dispose  //printed only once

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *