Reputation: 992
I have a method Foo
that returns a IDisposable
object. Oftentimes when this method is called, the return value is used. However, in this case I need the method to be called but don't need the return value. Is the correct thing to do to immediately call Dispose
on it? If so, does it matter which of the below I do?
Foo().Dispose();
or
using(Foo())
{
}
or just
Foo();
Upvotes: 3
Views: 389
Reputation: 4777
If an object implements IDisposable then you should call the Dispose method when you are finished with the object. Dispose is meant to release resources that should not be held until a GC (Garbage Collector) cycle (or things that are not covered by the GC). When the GC detects that an object is no longer used it will call the objects finalizer, but there is no way to predict when that will happen. Therefore, the IDisposable interface was created so that programmers could explicitly dispose of an object's resources (it doesn't delete the object, the GC still does that).
I think I would prefer
Foo().Dispose();
but it really doesn't matter (between the first two). If you just use "Foo();" then you are not respecting the Dispose pattern which would be incorrect. You may want to try to determine what sort of resources the object is creating, perhaps there is a way to get the information you need without creating an object that needs disposing.
Upvotes: 4