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

Tom Larsen tomar@apricot.com
Tue, 12 Oct 2004 21:29:44 -0700 (PDT)


On Tue, 2004-10-12 at 22:45, sarvesh wrote:
> Hi,
>
>             We know that using statement like the one below would
>
>
>
> using (MyResource myObject = new MyClass())
>
> {
>
>     myObject.DoSomething();
>
>
>
> }
>
> gets translated to,
>
>
>
>
>
> MyClass myObject= new MyClass();
>
> try
>
> {
>
>     myObject.DoSomething();
>
> }
>
> finally
>
> {
>
>     // Check for a null resource.
>
>     if (myObject!= null)
>
>         // Call the object's Dispose method.
>
>         ((IDisposable)myObject).Dispose();
>
> }
>
>
>
>
>
> The problem I am having is I havent been able to figure out what If
> someone did
>
>
>
> 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 ??
>
>
>
> Regards,
>
> sarvesh

Yes it would be disposed because once the exception is thrown you are
leaving the scope of the "try" and therefore are going to execute the
"finally".  If you are doing debugging you can always break down the
block or just remove the "using" to do extra testing.

Tom Larsen