How to use the C # 6 feature "Using Static"?

I am looking at a couple of new features in C # 6, in particular, "using static".

using static is a new use case that allows you to import static type elements directly into a scope. (The bottom of the blog post)

The idea is as follows, according to several tutorials that I found,
Instead:

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 function to use static classes:

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

However, this does not seem to work for me. I get an error in using saying:

The " using namespace " directive can only be applied to namespaces, " Console " is a type, not a namespace. Instead, use the " using static " directive

I am using visual studio 2015 and I have a build language version set to "C # 6.0"

What gives? Incorrect msdn blog example? Why is this not working?

+82
c # static visual-studio-2015 using
Aug 6 '15 at 9:46
source share
1 answer

The syntax seems to have changed slightly since these blog entries were written. As the error message shows, add static to the include statement:

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

Then your code will be compiled.




Note that this will only work for members declared as static .

For example, consider System.Math :

 public static class Math { public const double PI = 3.1415926535897931; public static double Abs(double value); // <more stuff> } 

When using static System.Math , you can simply use Abs(); .
However, you still have to use the PI prefix because it is not a static member: Math.PI; .

+122
Aug 6 '15 at 9:46
source share



All Articles