What needs to be done for a class to be used inside a using block

To enable a class to be used under a using() block, the class must implement the IDisposable interface with its own implementation of the Dispose() method.

public class MyClass : IDisposable {
    public void Dispose() {
      // implementation of Dispose method
    }
}

// in some other method
using(var myclass = new MyClass()) {
    // myclass instance is alive inside 
    // this block only
}

Dispose is never called by the .NET Framework; you must call it manually - preferably by wrapping its creation in a using() block.

To enable a class to be used under a using() block, the class must implement the IDisposable interface with its own implementation of the Dispose() method.

public class MyClass : IDisposable {
    public void Dispose() {
      // implementation of Dispose method
    }
}

// in some other method
using(var myclass = new MyClass()) {
    // myclass instance is alive inside 
    // this block only
}

Dispose is never called by the .NET Framework; you must call it manually – preferably by wrapping its creation in a using() block.


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 *