Using statements are null-safe C# with Example



Using statements are null-safe C# with Example

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

0 Comment's

Comment Form

Submit Comment