Search code examples
c#.net-2.0

Disposable Class


Please consider the following class:

public class Level : IDisposable
{
   public Level() { }

   public void Dispose() { }
}

My question is, if I call the Dispose method, will the class actually be disposed (garbage collected)?

ex:

Level level = new Level();
level.Dispose();

Thanks.


Solution

  • My question is, if I call the Dispose method, will the class actually be disposed?

    If by disposed you mean garbage collected, then no, this won't happen. What will happen when you call the Dispose method is, well, the Dispose method be called and its body executed.

    Also it is recommended to wrap disposable resources in a using statement to ensure that the Dispose method will always be called even in the event of an exception. So instead of manually calling it you could:

    using (Level level = new Level())
    {
        // ... do something with the level
    }
    

    Normally the Dispose method is used when the object holds pointers to some unmanaged resources and provides a mechanism to deterministically release those resources.