c# – When is it recommended that a class implement IDisposable?


I use the IOC pattern in my project which facilitates the procedure call of the type Resolver.Resolve<IPedido>().GerarPedido() , however, I didn't want to leave it "loose" like this, I would like to implement the IDisposable method to use it like this:

using (var pedido = Resolver.Resolve<IPedido>())
  1. Can I implement IDisposable in a simple class, in this example Pedido ? Would it be good practice?
  2. Does it have a processing cost?
  3. What is the best way to implement IDisposable in this example?


The function of the using{} block, in your own words, is not to "kill" an object so that it "doesn't get loose".
This is the responsibility of the garbage collector .

The Dispose() method, which is part of the IDisposable interface, is normally used to free resources allocated by the class that, if not freed, could create memory leaks when the object is collected by the GC.

The function of using is to allow classes that implement IDisposable to be used in such a way as to guarantee the execution of the Dispose() method at the end of its use, even if an exception is thrown.

Thus, the implementation of the IDisposable interface is only recommended when it is necessary to carry out some procedure after using the object and before it is collected by the GC.

Implementing that interface, by itself, does not guarantee that the Dispose() method is called, but it indicates to the user/consumer that it must do so.

Scroll to Top