C# 8 – Making Use of Using Declarations

C# 8 – Making Use of Using Declarations

With C# 9 just around the corner. This post will take a look at a little syntactic sugar known as using declarations in C# 8. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method. It guarantees that the dispose method will be called, even if the code throws an exception.

Still coding IDisposables the curly bracket way? Learn how to use the latest syntactic sugar for using statements in this C# 8 feature highlight.

With C## 9 just around the corner, it’s a good time to look back at some of the goodness in C## 8. This post will take a look at a little syntactic sugar known as using declarations.

Since time immemorial, C## programmers have been using the using statement to implement disposable classes safely. File I/O, databases, and web services all benefit from the using statement.

The only downside is that adding a using statement to your code introduces a new scope block and indentation level. C## 8 using declarations eliminate that requirement.

Review: the using keyword

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C## 8 using statements ensure that classes that implement the IDisposable interface call their dispose method. It guarantees that the dispose method will be called, even if the code throws an exception.

This guarantee is essential when the disposable object references lockable or finite resources like files and network connections. You don’t want your code locking resources up indefinitely because it blew up while trying to use that resource.

The following code is an example of the using statement in action. To run this code, spin up a new console app in Visual Studio 2019 or Visual Studio Code.

Or you can use an online IDE and copy this code into it. .NET Fiddle is nice for playing with new features and trying out code snippets, but be sure to set the Compiler field to .NET Core 3.1 if you use it.

using System;

namespace CSharpFeatures
{
    class Program
    {
        static void Main()
        {
            using (var disposableItem = new DisposableClass())
            {
                Console.WriteLine("Inside of the using statement");
            }
        }
    }

    class DisposableClass : IDisposable
    {
        public void Dispose()
        {
            // Release resources, close any connections, etc... 
            Console.WriteLine("I'm disposing!");
        }
    }
}

In C#, using statements define a new scope block. Any variables declared inside of a using statement are local to that block. At the end of that new scope the dispose method for that object is called.

Another way to ensure the correct use of disposable classes is to use a try-finally block. The finally keyword guarantees that the dispose method will be called.

using System;

namespace CSharpFeatures
{
    class Program
    {
        static void Main()
        {
            var disposableItem = new DisposableClass();
            try
            {
                Console.WriteLine("Inside of the try block");
            }
            finally
            {
                disposableItem.Dispose();
            }
        }
    }

    class DisposableClass : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("I'm disposing!");
        }
    }
}

This works, but the using statement is easier to read. There are fewer lines of code and less indentation.

csharp programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Developer Career Path: To Become a Team Lead or Stay a Developer?

For a developer, becoming a team leader can be a trap or open up opportunities for creating software. Two years ago, when I was a developer, ... by Oleg Sklyarov, Fullstack Developer at Skyeng company

Tracking a Developer’s Journey From Documentation Visit

Measuring website activity provides only half the story. See how to best track the developer's journey and what funnel stages makes sense for API-first products

Offshore Software Development - Best Practices

To make the most out of the benefits of offshore software development, you should understand the crucial factors that affect offshore development.

Hire Ruby on Rails Developer | Hire RoR Developer

#1 Ruby on Rails development company. Hire Ruby on rails developer or a team to build secure, scalable and complex web solutions with a quick turnaround time.