[Mono-list] RE: using Statement in c# and garbage collection

David Wright ichbin@shadlen.org
Wed, 13 Oct 2004 00:33:38 -0700


> using (MyResource myObject = new MyClass())
> 
> {
> 
>     myObject.DoSomething();
> 
> --   throw SomeException(" Exception thrown."; // assume an exception is
> thrown explicity. 
> 
> }
> What would happen now? Would the myObject get disposed ? Or would it stay ?
> What does the IL code look like in this situation ?? 

I am confused at your confusion. As you yourself pointed out, this is
equivalent to:

MyResource myObject = new MyClass();
try {
	myObject.DoSomething();
	throw SomeException("Exception thrown.");
} finally {
	myObject.Dispose();
}

whether an exception is thrown explicitly or by an invoked method makes
absolutely no difference. The exception gets passed up the call stack,
executing finally blocks along the way.

So to be painfully explicit: yes, myObject gets disposed.

If you really want to see the IL, write compilable code and view it with
ilDasm.