Search code examples
c#using

C#: using block: object re-initialization


Re-initialization within "using" block is a bad idea, to be avoided at all times. Still i am going to ask this:

Why does "using" call dispose on the original value and not on the last reference or re-initialization (which happens if try finally block is used)

MyClass b = new MyClass();// implements Idisposable
MyClass c = new MyClass();
MyClass a ; 

 using (a = new MyClass())
 {
                a = b;
                a = c;
 }

In the above code dispose will be called on original reference and not the newer referenced. This can be easily verified by printing something on console in the dispose method.

However with try{} finally code the last reference dispose method is called.

try
{
   a = new MyClass();
   a = b;
   a = c;
 }
  finally 
   {
   a.Dispose();
  }

MSDN : The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

Basically "using" translates to:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

Solution

  • The compiler generates this code:

    MyClass b = new MyClass();
    MyClass a;
    MyClass cs$3$000 = a = new MyClass();
    try {
      a = b;
    }
    finally {
      if (cs$3$000 != null) cs$3$000.Dispose();
    }
    

    The auto-generated cs$3$000 local variable implements the contract.