开发者

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

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?


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

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


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();
    }
}


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜