Auto-disposing? Empty using syntax?

What do you think? Should this code auto-dispose the X object instance created but not used? If you test it, you’ll see it does not:

public class X : IDisposable { … }
static void Main(string[] args)
    Get(); // Doesn't dispose result.

static X Get()
    Console.WriteLine("Getting X...");
    return new X();

As you can see, the Get() call in Main will cause the side effect of constructing a new X object, which is disposable. But Main doesn’t actually use that object – it’s interested just in other side effects caused by Get method to occur, such as to have the Getting X… string written to the output stream.

The compiler could easily infer that the caller doesn’t need the object and it might just inject a Dispose() call on the result of the call that is not put into a var. This would avoid the need of this empty using statement to do the disposal in an explicit way, which seems so awkward, and brings further questions – such as whether to do it or not – especially as X can be Task<T> and in that case it’s commonly used with .NET 4.5’s asynchronous code:

using(Get()) { } // Disposes result.

A possible reason against auto-disposing, though, might be that without the explicit using, maybe the caller is also interested in having the X object healthy (i.e. not disposed) in memory for the next undefined period of time – maybe X just adds itself as a listener to some static object events, for example, and in this case, disposing it blindly might cause unexpected results.

However, I personally think that at least the language should permit this syntax sugaring – and I wonder why nobody thought of it already, as C# reached version 7 this year!

using(Get()); // Doesn't compile!

Ah, I see the problem now! Actually the syntax should better be:

!using(Get()); // But still doesn't compile, of course! :-)

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in C# and tagged , , , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s