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

前端 未结 5 811
花落未央
花落未央 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();
        }
    }
    

提交回复
热议问题