Dombat


Software Engineering, Security, Management & Leadership. I work for Microsoft as an Application Development Manager (ADM). Views are mine.

Dombat

The way you use Using in C#8 is changing

6th December 2019

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?

Images shows rosalyn analyser warning with the message "dispose 'file' when no longer needed".

This is part of my personal refresh of C# series of blog posts.

Software Engineer with interests in security and business processes.

View Comments