Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 389
Paolo Tedesco Avatar asked Mar 26 '10 11:03

Paolo Tedesco


People also ask

Does dispose make an object null?

When you set a reference to null, it simply does that. It doesn't in itself affect the class that was referenced at all. Your variable simply no longer points to the object it used to, but the object itself is unchanged. When you call Dispose(), it's a method call on the object itself.

Does using statement Call dispose?

The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.

What statement describes a Dispose method?

C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.

Can we declare object as null?

Technically, it will have a value of null. However, the C# compiler will not let you use the object until it has been explicitly assigned a value (even if that value is null ). no difference, both are null.


4 Answers

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

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

like image 74
reko_t Avatar answered Oct 02 '22 04:10

reko_t


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();
    }
}
like image 24
João Angelo Avatar answered Oct 02 '22 03:10

João Angelo


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.

like image 23
Darin Dimitrov Avatar answered Oct 02 '22 04:10

Darin Dimitrov


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

like image 36
oli Avatar answered Oct 02 '22 05:10

oli