C# 8.0 Enhanced Using Declaration

As we all aware using keyword is been used to ensure that the Dispose() method will be called on a type object implemented IDisposable interface when it reaches declared block as shown below.
  1. using(Stream myStream = new MemoryStream(int.MaxValue))  
  2. {  
  3. }  
Here, when the block reaches by the runtime, Dispose() method will be called on myStream object by the runtime as it is declared in using block.
 
In C# 8.0, this using block made easier to avoid some nesting using blocks as follows.
  1. using(Stream myStream = new MemoryStream(int.MaxValue))  
  2.    {  
  3.       using (Stream myStream1 = new MemoryStream(int.MaxValue))  
  4.       {  
  5.       }  
  6. }  
As we can see in the above statement, we declared inner using block and it can go to any extent. In C# 8.0, it made simple as below.
  1. using Stream myStream = new MemoryStream(int.MaxValue);  
  2. using Stream myStream1 = new MemoryStream(int.MaxValue);  
As we can see, just need to prefix these variables by using keyword. The runtime will make sure to call the Dispose method when it comes out of the declared block.
 
Happy Coding ??