Using statements are null-safe
suggest changeYou don’t have to check the IDisposable object for null. using will not throw an exception and Dispose() will not be called. The first DoSomething below throws, so the null check after it is not reached:
DisposableObject TryOpenFile()
{
return null;
}
// disposable is null here, but this does not throw an exception
using (var disposable = TryOpenFile())
{
// this will throw a NullReferenceException because disposable is null
disposable.DoSomething();
if(disposable != null)
{
// here we are safe because disposable has been checked for null
disposable.DoSomething();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents