Will Dispose() be called in a using statement with a null object?

Paolo Tedesco picture Paolo Tedesco · Mar 26, 2010 · Viewed 33k times · Source

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?

Answer

reko_t picture reko_t · Mar 26, 2010

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

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