Thursday, July 23, 2015

C# 6: importing static members of type

On Github you can find a great doc on new features of C# 6 available now in Visual Studio 2015 released July 20 2015:

https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6

In C# 6 it is easy to import static members of type and usually this is illustrated from types of .NET Framework. But nothing prevents you to import static members of your own types.

How to do this? Imagine you developed some great and very useful library with any functionality wrapped into static classes and methods:
using static System.Math;
using System;

namespace MathLibrary
{
    static public class MathClass
    {
        static public double round(double a)
        {
            return Round(a, 2, MidpointRounding.AwayFromZero);
        }
    }
}
Of course, in real life it will have a lot of methods and they will be much more complex. But it is not important for us now. To use round() in a new C# 6 way we just need to do the following:
using static System.Console;
using static MathLibrary.MathClass;

class Program
{
    static void Main()
    {  
        WriteLine(round(5.555).ToString("0.00"));
        WriteLine(round(2.995).ToString("0.00"));
        WriteLine(round(3.223).ToString("0.00"));
    }
}
Target framework for this code can be any - from .NET Framework 2.0 to .NET Framework 4.6 since this specific code doesn't require anything specific. But it can't be compiled in Visual Studio 2013.

No comments:

Post a Comment