Using Declarations In C# 8

I recently came across a feature that was introduced in C# 8. It actually threw me through a loop because I first saw it used in some code I was reviewing. In a moment of “confidently incorrect”, I told the developer that they definitely had to change the code because clearly it wouldn’t work (If it would compile at all).

Of course the egg on my face ensued with a quick link to the documentation and a comment along the lines of “Shouldn’t you have written this on that blog?”.

Oof.

The feature I am talking about is “Using Declarations”. I think every time I’ve seen this feature mentioned, I’ve thought it referred to your standard usings at the top of your .cs file. Something like this :

using System;
using System.IO;

But in fact, it revolves around the use of using to automatically call dispose on objects. The code in question that I was reviewing looked something like this (And note, this is a really dumb example so don’t read into the code too much).

static int countLines()
{
    using var fileStream = File.OpenRead("myfile.txt");
    using var fileReader = new StreamReader(fileStream);
    var lineCount = 1;
    var line = string.Empty;
    while((line = fileReader.ReadLine()) != null)
    {
        lineCount++;
    }
    return lineCount;
}

I mentioned to the developer…. “Well how does that using statement work?” I had just assumed it functioned much like how an If statement works without braces. e.g. It will only affect the next line like so :

if(condition)
    DoThis();
ButThisIsNotAffectedByCondition();

But in fact this is a new way to do using statements without braces.

Now, placing a using statement like so :

using var fileStream = File.OpenRead("myfile.txt");

Actually means that the object will be disposed when control leaves the scope. The scope could be a method, a loop, a conditional block etc. In general, if it leaves an end brace } somewhere, the object will be disposed.

Why is this handy? Well without it, you would have to have large amounts of indenting, and generally that indentation is for the entire method body anyway. For example :

static int countLines()
{
    using (var fileStream = File.OpenRead("myfile.txt"))
    {
        using (var fileReader = new StreamReader(fileStream))
        {
            var lineCount = 1;
            var line = string.Empty;
            while ((line = fileReader.ReadLine()) != null)
            {
                lineCount++;
            }
            return lineCount;
        }
    }
}

Much less prettier, and it doesn’t afford us anything extra (In this case) than just doing the using declaration.

The one thing you may still want to use braces for is if you wish to really control when something is disposed, even without code leaving the current control scope. But otherwise, Using Declarations are a very nifty addition that I wish I knew about sooner.

1 thought on “Using Declarations In C# 8”

Leave a Comment