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
Default image
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

One comment

Leave a Reply to .NET Core Garbage Collection Simplified - ReferbruvCancel Reply

Your email address will not be published.