There are certain static methods such as Process.Start()
and File.Create()
that construct and return IDisposable
instances that are often discarded. It's so normal to use these methods as though they return void
that if you aren't paying attention you might miss the fact that they even have return values at all.
I understand that it's good practice to always dispose of IDisposable
instances. Does this apply to unused return values? Instead of writing Process.Start(processPath);
should you always write Process.Start(processPath).Dispose();
?
I'd think this would be an obvious yes but I have to second guess myself because I only ever see it done without the Dispose()
. Does C# perhaps have some automatic way of handling those situations?
In most of the cases, prefered way of dealing with IDisposable
instances is by using using
statement:
using (var file = File.Create())
{
//use file instance
}
This syntactic sugar will make sure that file instance is explicitly disposed after you exit using
statement block. Under the hood, it actually wraps your code into try/finally block.
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