For instance I have a method
SomeMethod(Graphics g)
{
...
}
If I will call this method in a manner
SomeMethod(new Graphics())
Will my graphics object be autodisposed or I should call g.Dispose() manually in the end of the method?
SomeMethod(Graphics g)
{
...
g.Dispose();
}
Disposable objects will not get autodisposed (the closest they can get to that is implementing a Finalizer that calls
Disposeif necessary). You have to do this manually by callingDispose()or by using it with ausingblock.If you want to auto dispose the object, you could do this:
The using block ensures that the
Dispose()method is called automatically as soon as the block ends (so in this case, afterSomeMethodreturns or throws an exception).Note: You should dispose the object at the location near where you created it, if possible. Taking in a valid object and disposing of it inside the method could cause confusion.
Graphics and probably most if not all BCL classes implementing this interface will also call
Dispose()when the Finalizer is called. This is part of a proper implementation ofIDisposable. However you never know when the finalizer is called and you should not rely on this implementation detail if you need your object to be deterministically disposed of.