Cerbrus Cerbrus - 3 months ago 8
C# Question

How do I use the C#6 "Using static" feature?

I'm having a look at a couple of the new features in C# 6, specifically,
"using static".

The idea is as follows, according to a couple of tutorials I found,

Instead of:

using System;

class Program
{
static void Main()
{
Console.WriteLine("Hello world!");
Console.WriteLine("Another message");
}
}


You can omit the repeated
Console
statement, using the new C# 6 feature of using static classes:

using System.Console;

class Program
{
static void Main()
{
WriteLine("Hello world!");
WriteLine("Another message");
}
}


However, this doesn't appear to be working for me. I'm getting an error on the
using
statement, saying:


"A '
using namespace
' directive can only be applied to namespaces; '
Console
' is a type not a namespace. Consider a '
using static
' directive instead"



I'm using visual studio 2015, and I have the build language version set to "C# 6.0"

What gives? Is the msdn blog's example incorrect? Why doesn't this work?

Answer

It appears the syntax has slightly changed since those blog posts were written. As the error message suggests, add static to your include statement:

using static System.Console;
//      ^
class Program 
{ 
    static void Main() 
    { 
        WriteLine("Hello world!"); 
        WriteLine("Another message"); 
    } 
}

Then, your code will compile.

Comments