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 Dispose
if necessary). You have to do this manually by calling Dispose()
or by using it with a using
block.
If you want to auto dispose the object, you could do this:
using (var g = new Graphics()) {
SomeMethod(g);
}
The using block ensures that the Dispose()
method is called automatically as soon as the block ends (so in this case, after SomeMethod
returns 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 of IDisposable
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With