C# 6 features – Static using 2


Facebooktwittergoogle_pluslinkedinmail

One more C# 6 syntactic sugar feature is static using.  The feature eliminate explicit reference to the type when invoking a static method.

Here is an example of static using with System.Console class.

using static System.Console;

namespace StaticUsingExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var initialColor = ForegroundColor;
            ForegroundColor = System.ConsoleColor.Red;
            WriteLine("RED");
            ForegroundColor = System.ConsoleColor.Blue;
            WriteLine("BLUE");
            ForegroundColor = initialColor;
        }
    }
}

Next interesting example is usage of System.Math class.

using static System.Math;

namespace StaticUsingExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            double a = 4;
            double result = Sqrt(a);
        }
    }
}

Interesting side effect is that static using lets you introduce extension methods from specific class, instead of all extension methods within namespace.

Here is an interesting article showing which MSCORELIB Classes work with static using in C# 6.

 

Facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *

2 thoughts on “C# 6 features – Static using

  • Daniels

    Hello, I dont inderstand the difference between static using between old versions and this one ?
    Thank you for your blog is so interesting

    • Mariusz Bojkowski Post author

      Hi Daniels,
      The difference is with what the using statement is referring to. The regular using can be used only with namespaces to expose classes inside the namespace. The static using, on the other hand, can be used with static classes to expose static methods of the static class.