C# 6.0 Language Features – Static Using Statements

Welcome to C# 6.0 language features article series. As you might have heard about Visual Studio 2015 and .Net framework 4.6 announcements in various Microsoft events earlier, one of the most exciting news was the next version of C# language, which is 6.0 and new features added to it. C# has come a long way since 2002 when C# 1.0 was released along with Visual Studio. Since then with every major release of .Net framework, C# became better and better language, which has tremendously helped application developers to minimize the code complexity and focus on business functionality. With the new version of .Net framework and Visual Studio around the corner, you can start learning new language features today using Visual Studio 2015 preview release. There are many useful features added to the language and I don’t know at the moment, how many articles I will write in this series, but it will probably something like this.

  1. Static using statements – This article
  2. Auto property initializers
  3. Null conditional operator
  4. String interpolation
  5. nameof operator
  6. Declaration expressions

Static Using Statements

Declaration of static using statements allows application developer to eliminate an explicit reference to static type when invoking static method. It also allows you introduce only the extension methods on a specific class, rather than all extension methods within a namespace. Code snippet defined below shows how you can use static using statements.

using System;
using static System.Console;

namespace LanguageFeatures
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleColor textColor = ForegroundColor;
            try
            {
                ForegroundColor = ConsoleColor.Red;
                Write("Enter your name ");

                ForegroundColor = ConsoleColor.Blue;
                string name = ReadLine();

                ForegroundColor = ConsoleColor.Red;
                WriteLine("Hello {0}, welcome to C# 6.0!", name);

                ReadLine();
            }
            finally
            {
                ForegroundColor = textColor;
            }
        }
    }
}

In this example, we have defined a static using statement for System.Console type. This allows us to call static methods like Write, WriteLine, ReadLine without explicitly specifying the containing type Console. Although it’s more like a syntactic sugar to the C# program, however it still allows you to write the code that’s easier to read and write.

Hope that was helpful.

Leave a Reply