Using Declarations In C# 8

Introduction

 
In C# 8, the using declaration syntax was introduced. This gives our code the benefits of IDisposable, without the extra noise that using statements can introduce.
 

IDisposable

 
If our class has some expensive resource allocation, we might want to deterministically free that resource as soon as we're done using it. We achieve this in C# by implementing the IDisposable interface. You must define a Dispose() method, and within that method you can free any resources explicitly.
  1. class Resource : IDisposable  
  2. {  
  3.     public Resource()  
  4.     {  
  5.         Console.WriteLine("Resource created...");  
  6.     }  
  7.     public void Dispose()  
  8.     {  
  9.         Console.WriteLine("Resource disposed..");  
  10.     }  
  11. }  

The Old Way

 
Since we're following the IDisposable convention, we can use the using statement syntax which will automatically call Dispose() when the scope ends.
  1. using (var resource = new Resource())  
  2. {  
  3.     Console.WriteLine("Using resource...");  
  4. }  
Output
  1. Resource Created...  
  2. Using resource...  
  3. Resource Disposed...  
The New Way, C# 8 Using Declarations 
  1. using var resource = new Resource();  
  2. Console.WriteLine("Using resource...");  
Output
  1. Resource Created...  
  2. Using resource...  
  3. Resource Disposed...   
Example - File I/O
  1. try  
  2. {     
  3.     using var sr = new StreamReader("test.txt");  
  4.     Console.WriteLine(sr.ReadToEnd());  
  5. }  
  6. catch (IOException e)  
  7. {  
  8.     Console.WriteLine("Error while loading the file.");  
  9. }  

Conclusion

 
This syntax feature is so simple, and can not only reduce extra indentations in your code, I think it also reduces cognitive burden when reading the code.
 
As always I hope you find this article helpful. Please share any feedback or article suggestions. Thanks for reading!