200

Is it safe to use the using statement on a (potentially) null object?
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?

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
  • 1
    Related http://stackoverflow.com/questions/2513035 – Brian Rasmussen Mar 26 '10 at 11:37
  • To answer your last question directly [from the language spec](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#1314-the-using-statement): `If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.` – Eric Mutta May 24 '23 at 16:47

5 Answers5

194

Yes, Dispose() is only called on non-null objects:

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

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
reko_t
  • 55,302
  • 10
  • 87
  • 77
  • 41
    Note that even if your variable is null, the using block is executed, and if you reference your variable inside the using block without first null-checking it, you WILL get NullReferenceException. To prevent misinterpretation, this answer should state: "Yes, `Dispose()` is only called on non-null objects". – surfen Nov 28 '11 at 09:05
46

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
{
    // etc...
}
finally
{
    if(x != null)
    {
        x.Dispose();
    }
}
Andriy Volkov
  • 18,653
  • 9
  • 68
  • 83
João Angelo
  • 56,552
  • 12
  • 145
  • 147
22

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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

oli
  • 84
  • 1
-3

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

malay
  • 1,434
  • 4
  • 17
  • 28