Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it important to dispose unused IDisposable return values? [duplicate]

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?

like image 412
Kyle Delaney Avatar asked Dec 18 '22 23:12

Kyle Delaney


1 Answers

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.

like image 188
Darjan Bogdan Avatar answered Dec 29 '22 11:12

Darjan Bogdan