Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autodisposing objects

Tags:

c#

.net

dispose

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();
}
like image 633
TOP KEK Avatar asked Apr 11 '12 07:04

TOP KEK


1 Answers

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.

like image 125
Botz3000 Avatar answered Sep 23 '22 19:09

Botz3000