It seems that in most cases the C# compiler could call Dispose() automatically. Like most cases of the using pattern look like:
public void SomeMethod()
{
...
using (var foo = new Foo())
{
...
}
// Foo isn't use after here (obviously).
...
}
Since foo isn’t used (that’s a very simple detection) and since its not provided as argument to another method (that’s a supposition that applies to many use cases and can be extended), the compiler could automatically and immediately call Dispose() without the developper requiring to do it.
This means that in most cases the using is pretty useless if the compiler does some smart job. IDisposable seem low level enough to me to be taken in account by a compiler.
Now why isn’t this done? Wouldn’t that improve the performances (if the developpers are… dirty).
A couple of points:
Calling
Disposedoes not increase performance.IDisposableis designed for scenarios where you are using limited and/or unmanaged resources that cannot be accounted for by the runtime.There is no clear and obvious mechanism as to how the compiler could treat
IDisposableobjects in the code. What makes it a candidate for being disposed of automatically and what doesn’t? If the instance is (or could) be exposed outside of the method? There’s nothing to say that just because I pass an object to another function or class that I want it to be usable beyond the scope of the methodConsider, for example, a factory patter that takes a
Streamand deserializes an instance of a class.And I call it:
Now, I may or may not want that
Streamto be disposed of when the method exits. IfFoo‘s factory reads all of the necessary data from theStreamand no longer needs it, then I would want it to be disposed of. If theFooobject has to hold on to the stream and use it over its lifetime, then I wouldn’t want it to be disposed of.Likewise, what about instances that are retrieved from something other than a constructor, like
Control.CreateGraphics(). These instances could exist outside of the code, so the compiler wouldn’t dispose of them automatically.Giving the user control (and providing an idiom like the
usingblock) makes the user’s intention clear and makes it much easier to spot places whereIDisposableinstances are not being properly disposed of. If the compiler were to automatically dispose of some instances, then debugging would be that much more difficult as the developer had to decipher how the automatic disposal rules applied to each and every block of code that used anIDisposableobject.In the end, there are two reasons (by convention) for implementing
IDisposableon a type.IDisposablethat should be disposed of when this object’s lifetime is over.In the first case, all such types are supposed to implement a finalizer that calls
Disposeand releases all unmanaged resources if the developer fails to do so (this is to prevent memory and handle leaks).