views:

261

answers:

5

Is it safe to use the using statement on a (potentially) null object?
I.e. consider the following example:

class Test {
    IDisposable GetObject(string name) {
        // returns null if not found
    }

    void DoSomething() {
        using (IDisposable x = GetObject("invalid name")) {
            if (x != null) {
                 // etc...
            }
        }
    }
}

Is it guaranteed that Dispose will be called only if the object is not null, and I will not get a NullReferenceException?

note: from the link in the accepted answer:

The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object): C#

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

You should be ok with it:

using ((IDisposable)null) { }

No exception thrown here.

Side note: don't mistake this with foreach and IEnumerable where an exception will be thrown.

Darin Dimitrov
+2  A: 

The expansion for using checks that the object is not null before calling Dispose on it, so yes, it's safe.

In your case you would get something like:

IDisposable x = GetObject("invalid name");
try
{
    if (x != null) 
    {
        // etc...
    }
}
finally
{
    if(x != null)
    {
        x.Dispose();
    }
}
João Angelo
A: 

You will not get null reference exception as per my experience. It will be simply ignored.

malay
+7  A: 

Yes, it only calls it on non-null objects:

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

reko_t
+1  A: 

Yes, before Disposing the reference will be null-checked. You can examine yourself by viewing your code in Reflector.

oli