Reputation: 13649
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.
Upvotes: 2
Views: 11054
Reputation: 529
In .NET Disposing and garbage collection are two different things:
The point of disposing is to release any resources that are either not managed by .NET (like manually allocated memory) or that have interests in being released as soon es they aren't needed anymore (like file handles or network connections).
The purpose of garbage collection is to free memory that is managed by .NET (like normal objects).
So, as others pointed out: your object will not necessarily be garbage collected when it gets disposed.
Upvotes: 0
Reputation: 66388
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;
}
}
Upvotes: 3
Reputation: 62256
If you call Dispose()
it will be disposed, which doesn't absolutely mean that it will be garbage collected,seems to me that is your question, if not please clarify.
Upvotes: 0
Reputation: 37761
No, the instance won't be garbage collected due to calling Dispose. The Dispose method is where you can release any resources held by the instance, it isn't about disposing the instance itself.
Upvotes: 0
Reputation: 1038870
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.
Upvotes: 9
Reputation: 161783
Each class that implements IDisposable
defines what it means to be disposed. By that line of reasoning, yes, your class will be as disposed as it wants to be.
Upvotes: 0