C# 6 features – Static using

C# 6; Static using example

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 *