Introduction
In today’s article, we will look at a new feature introduced with C# 8.0. This is not entirely a new feature, but an enhancement to an existing feature. This is the improvement in the use of the using declaration. We use the using declaration to automatically dispose of an object once it is out of the scope of the using statement. We will see the enhancement of this feature introduced with C# 8.0 in this article. C# 8.0 is supported on .NET Core 3.x and .NET Standard 2.1.
Creating a Simple Console Application
We start by creating a simple console application using Visual Studio 2019 community edition. The framework used is .NET Core 3.1.
In this application, we read a list of string elements and then write them into a text file on the local drive. However, we want to skip any text which contains the words “SkipMe”.
We would normally write this application as shown below:
- using System;
- using System.Collections.Generic;
- namespace CSharp8Features {
- classProgram {
- staticvoid Main(string[] args) {
- var texts = new List < string > {
- "Line1",
- "SkipMe",
- "Line2",
- "Line3",
- "SkipMe"
- };
- Console.WriteLine($ "Total lines missed in Old Format are {WriteToFileOld(texts)}");
- Console.ReadKey();
- }
- //Old method of using the USING declartion
- staticint WriteToFileOld(List < string > texts) {
- //We declare this outside the using block
- var missedLines = 0;
- using(var file = new System.IO.StreamWriter(@ "C:\Temp\OldFormatFile.txt")) {
- foreach(string text in texts) {
- if (!text.Contains("SkipMe")) file.WriteLine(text);
- else missedLines++;
- }
- }
- return missedLines;
- }
- }
- }
Here, you can see that we are writing by using the Stream Writer which is disposed of when the using statement goes out of scope. However, any variable we need to use outside this block must also be declared outside the block as we see in the case of the “missedLines” variable.


Roshan RathodPosted Aug 10, 2020, 4:49 AM
Good ..keep it up...sir