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

前端 未结 5 749
花落未央
花落未央 2020-12-04 18:37

Is it safe to use the using statement on a (potentially) null object?
Consider the following example:

class Test {
    IDisposable GetObject         


        
相关标签:
5条回答
  • 2020-12-04 19:06

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 19:06

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

    0 讨论(0)
  • 2020-12-04 19:12

    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.

    0 讨论(0)
  • 2020-12-04 19:15

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

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

    0 讨论(0)
  • 2020-12-04 19:18

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

    0 讨论(0)
提交回复
热议问题