Disposable Class

10,112

Solution 1

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.

Solution 2

I assume that what you are after is a way to know that Dispose() was called?

You can do that either in the consuming code by setting the instance to null after disposing:

Level level = new Level();
//do stuff with the instance..
level.Dispose();
level = null;

//in other place:
if (level != null)
{
    //still available
}

Or in the class itself, add boolean flag and in every method check for it:

public class Level : IDisposable
{
    private bool disposing = false;
    public Level() { }

    public void Foo()
    {
        if (disposing)
            return;
        MessageBox.Show("foo");
    }

    public void Dispose()
    {
        if (disposing)
            return;
        disposing = true;
    }
}
Share:
10,112
yonan2236
Author by

yonan2236

I love my cat...

Updated on June 04, 2022

Comments

  • yonan2236
    yonan2236 almost 2 years

    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.