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
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With