C#: Using Declaration

Introduced in C# 8.0, the using-declaration language enhancement eliminates nested using-statements. The following code:

using System.IO;
class Program
{
  static void Main(string[] args)
  {
    var filename = "hello.txt";
    using (var stream = new FileStream(filename, FileMode.Create))
    {
      using (var writer = new StreamWriter(stream))
      {
        writer.WriteLine("Hello, World!");
      }
    }
  }
}

is improved with using declarations to the following:

using System.IO;
class Program
{
  static void Main(string[] args)
  {
    var filename = "hello.txt";
    using var stream = new FileStream(filename, FileMode.Create);
    using var writer = new StreamWriter(stream);

    writer.WriteLine("Hello, World!");
  }
}
Questions, comments, and responses are welcomed and appreciated.

Leave a Reply