Given the code
void Blah(Thing Boz)
{
DisposableThing Foo = new DisposableThing();
Boz.SomeMethod(Foo);
}
the compiler would have no trouble determining that after the method exits, the reference Foo
will no longer be needed. If, at that time, there would be no other reference, anywhere in the universe, to the DisposableThing
identified by that reference, then that DisposableThing
should have its Dispose
method called before it's abandoned. The problem is that the compiler has no way of knowing whether SomeMethod
might have stored a reference to that object somewhere else.
In the vast majority of cases where an IDisposable
object is created, it will get passed into methods whose details the compiler knows nothing about. Consequently, the compiler has no way of knowing whether a particular reference to the object will be the only reference to the object at the time it goes out of scope.
If the method had been written as:
void Blah(Thing Boz)
{
using (DisposableThing Foo = new DisposableThing())
{
Boz.SomeMethod(Foo);
}
}
that would instruct the compiler to call Dispose
upon the newly-created object after Boz.SomeMethod()
returns. The compiler won't try to figure out whether Boz.SomeMethod()
might have kept a reference--the using
statement will call Dispose
regardless.