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

ID : 20308

viewed : 12

Tags : c#idisposableusingc#

Top 5 Answer for c# - Will Dispose() be called in a using statement with a null object?

vote vote

95

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

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

vote vote

88

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

76

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.

vote vote

64

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

vote vote

60

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

Top 3 video Explaining c# - Will Dispose() be called in a using statement with a null object?

Related QUESTION?