Essential C# Using Statement  Suggest an edit

Using statements are null-safe

You don’t have to check the IDisposable object for null. using will not throw an exception and Dispose() will not be called:

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


Table Of Contents
22 Enum
25 GUID
59 Using Statement
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close