ICYMI C# 8 New Features: Write Less Code with Using Declarations

This is part 2 in a series of articles.

One nice little enhancement introduced in C# 8 helps to simplify code that uses disposable objects.

For example consider the following:

class MyDisposableClass : IDisposable
{
    public void Dispose()
    {            
        Console.WriteLine("Disposing");
    }

    public void Run() 
    {
        Console.WriteLine("Running");
    }
}

Prior to C# 8, if you wanted to use a disposable object (something that implements IDisposable) then you would usually use a using block as follows:

private static void Process()
{
    using (var x = new MyDisposableClass())
    {
        x.Run();
    }
}

At the end of the using block, the Dispose() method is called automatically.

With C# 8, instead of the using block, you can instead use a using declaration:

private static void Process()
{
    using var x = new MyDisposableClass();

    x.Run();
}

Notice in the preceding code, with a using declaration there is no need for the additional {}. When using a using declaration, the Dispose() method is called automatically at the end of the Process() method. Just as with the using block approach, if an exception occurs within the Process() method then Dispose() will still be called.

Using declarations help to keep code less cluttered because you have fewer braces {} and one level less of indenting.

If you have multiple usings, for example:

private static void Process()
{
    using (var x = new MyDisposableClass())
    using (var y = new MyDisposableClass())
    using (var z = new MyDisposableClass())
    {
        x.Run();
        y.Run();
        z.Run();
    }
}

You can rewrite this in C# 8 as follows:

private static void Process()
{
    using var x = new MyDisposableClass();
    using var y = new MyDisposableClass();
    using var z = new MyDisposableClass();

    x.Run();
    y.Run();
    z.Run();
}

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading