What is new in Using declarations of C# 8.0?

C#

The second new feature in C#8.0 is “using-declaration“. using-declaration is nothing just better resource management improvement. So with the help of this feature, we can define the scope of a resource in the program. That resource will be available within that scope and then it will be disposed of.

Using statement (before C#8.0)

As a C# developer you may know, we have a using statement to define the scope of the managed type objects and ensures that an Idisposable object is disposed at the end of scope with the proper cleanup. We don’t need to worry about disposing of the object, everything is automatically handled for us.

static int WriteToFile(IEnumerable lines)
{
int lineswritten = 0;
using (var file = new System.IO.StreamWriter("WriteLines.txt"))
{
foreach (string line in lines)
{
if (!line.Contains("Second"))
{
file.WriteLine(line);
lineswritten++;
}
}
} // file is disposed here

return lineswritten;
}

Using declaration (New in C#8)

The new feature, the using-declaration does not require us to define the scope of the object. It is instead automatically handled by the compiler itself. While in the case of using statement the scope of the object declared using the using statement is the scope in which it is declared.

Let us understand this with below example:

static int WriteToFile(IEnumerable lines)
{
using var file = new System.IO.StreamWriter("WriteLines.txt");
int lineswritten = 0;
foreach (string line in lines)
{
    if (!line.Contains("Sachin"))
    {
        file.WriteLine(line);
        lineswritten++;
    }
}

return lineswritten;
// file is disposed here
}

Common in Both :

1. In both using statements or using-declaration, the compiler generates the call to Dispose() automatically.
2. If the resource is not disposable then the compiler generates an error.