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#
- static int FindOccurencesOnLines(string wordToFind)
- {
- int searchCount = 0;
- string line = string.empty();
- (using sr = new System.IO.StreamReader("sample.txt"))
- {
- while (line = sr.ReadLine())
- {
- if (Line.Contains(wordToFind))
- {
- searchCount++;
- }
- }
-
-
- }
-
- return searchCount;
- }
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>;
- static int FindOccurencesOnLines(string wordToFind)
- {
- int searchCount = 0;
- string line = string.empty();
- using var sr = new System.IO.StreamReader("sample.txt");
-
- while (line = sr.ReadLine())
- {
- if (Line.Contains(wordToFind))
- {
- searchCount++;
- }
- }
-
- return searchCount;
-
- }