Using Declaration In C# 8.0

You already know the using keyword in C#. The same keyword in C# 8.0 (.Net 3.0) can be used in declaring variables. It tells the compiler that the variable being declared should be disposed when the scope of the variable is ended. We will see how to use it in declaration of variable.

Code in earlier version of C#
  1. static int FindOccurencesOnLines(string wordToFind)  
  2. {  
  3.     int searchCount = 0;  
  4.     string line = string.empty();  
  5.     (using sr = new System.IO.StreamReader("sample.txt"))  
  6.     {  
  7.         while (line = sr.ReadLine())  
  8.         {  
  9.             if (Line.Contains(wordToFind))  
  10.             {  
  11.                 searchCount++;  
  12.             }  
  13.         }  
  14.           
  15.     // sr is disposed here  
  16.     }  
  17.   
  18.     return searchCount;    
  19. }  

In C# version 8.0, it can be written with the using declaration of variable.

In the below code variable sr of type StreamReader is declared within method FindOccurencesOnLines with using keyword. like using var sr. StreamReader scope will end when the method FindOccurencesOnLines execution ends. 
 
Syntax
 
using <datatype> <variable name>;
  1. static int FindOccurencesOnLines(string wordToFind)  
  2. {  
  3.     int searchCount = 0;  
  4.     string line = string.empty();  
  5.     using var sr = new System.IO.StreamReader("sample.txt");  
  6.       
  7.     while (line = sr.ReadLine())  
  8.     {  
  9.         if (Line.Contains(wordToFind))  
  10.         {  
  11.             searchCount++;  
  12.         }  
  13.     }  
  14.   
  15.     return searchCount;  
  16.     // sr is disposed here