If you have been writing C# for any length of time, you will know that it has always had a level of nesting. The use of using statements in C# don’t make this any better. Now, with the release of C# 8.0, new C# features have been introduced that make developers lives much easier. C# 8.0 using declarations is just one of those new features.
Looking for Something Else? Try these links instead:
- Enabling C# 8 in Visual Studio 2019
- Visual Studio IntelliCode – AI For your Code
- Extension Methods Are Easy with C#
- The Unbelievably Powerful Multi Select
With the C# 8.0 release date still fresh in our minds (September 2019), you can be excused for not having played with all the new features yet. C# 8.0 using declarations offers a simple, yet effective approach to avoiding unnecessary nesting in your code.
Using Statements the Old Way
Consider the code snippet below. Here you can see the old way of writing a using statement. The variable fle is disposed of at the end of the using statement.
static int WriteFile(List<string> lines)
{
var iCommentsSkipped = 0;
using (var fle = new StreamWriter("OutputFile.txt"))
{
foreach (var line in lines)
{
if (!line.StartsWith("#"))
fle.WriteLine(line);
else
iCommentsSkipped += 1;
}
} // fle disposed here
return iCommentsSkipped;
}
Why use the curly braces anyway. The intent is quite clear when you see the word using. That tells me, that I only need this variable while it is useful to me. When I no longer need it, get rid of it.
C# 8.0 to the rescue
With C# 8.0 using declarations, you can simply omit the curly braces. I’m telling the code that I want my resource cleaned up after use. Consider the C# 8.0 code snippet below:
static int WriteFile(List<string> lines)
{
using var fle = new StreamWriter("OutputFile.txt");
var iCommentsSkipped = 0;
foreach (var line in lines)
{
if (!line.StartsWith("#"))
fle.WriteLine(line);
else
iCommentsSkipped += 1;
}
return iCommentsSkipped;
} // fle disposed here
The using becomes a using declaration. This is a local variable declaration with a using keyword in front, which means that the resource is disposed of at the end of the current statement block. To illustrate this, let’s debug our code.
C# 8.0 Using Declarations in Action
With the break point set, the using declaration is passed and the variable fle is still in scope.
You can see this in the Watch window.
You will also see the fle variable in the Locals window.
Moving past the break point, and exiting the method, the fle object is cleaned up and eventually disposed of.
C# 8.0 using declarations results in much cleaner code.
Conclusion
I would definitely say that while your methods conform to some of the SOLID principles (e.g. small methods that do one thing and one thing only), then new features such as the new using declaration will work really well.
Stay tuned for more articles on C# 8.0 and have a look at the official Microsoft documentation regarding the C# 8.0 new features.