The way you use Using in C#8 is changing
The way we write Using blocks in C#8 is chnaging to make the code more readable and maintainable.
Hopefully you know about using Using to ensure that Disposable objects are disposed when going out of scope? Many a memory leak has occured when this hasn't happened.
Have a look at this traditional C#. Basically a StreamWriter is created, a line is written to the file then it gets disposed when it drops out the curly brackets.
internal static void UsingTestOldWay()
{
using (var file = new StreamWriter("c:\\test.txt"))
{
file.WriteLine(@"this is a test!!!");
}
}
Well, in C#8 (.NetCore3.X) the syntax has slightly been simplifer to make code more readable. Have a look at this subtle difference.
internal static void UsingTestNewWay()
{
using var file = new StreamWriter("c:\\test.txt");
file.WriteLine(@"this is a test!!!");
}
Did you notice the difference? It reduces indentation and just makes the code a little bit nicer. Less { } all over the place makes for neater and easier to read code.
Dispose Warnings
Interestingly, I have a whole load of Rosalyn scanners installed to try them out. I'm still getting warnings to Dispose the variable, even though the code is valid and compiles ok. Maybe the scanners haven't yet caught up?
This is part of my personal refresh of C# series of blog posts.