Page 177 - CSharp/C#
P. 177

Chapter 25: C# 6.0 Features




        Introduction



        This sixth iteration of the C# language is provided by the Roslyn compiler. This compiler came out
        with version 4.6 of the .NET Framework, however it can generate code in a backward compatible
        manner to allow targeting earlier framework versions. C# version 6 code can be compiled in a fully
        backwards compatible manner to .NET 4.0. It can also be used for earlier frameworks, however
        some features that require additional framework support may not function correctly.


        Remarks



        The sixth version of C# was released July 2015 alongside Visual Studio 2015 and .NET 4.6.

        As well as adding some new language features it includes a complete rewrite of the compiler.
        Previously csc.exe was a native Win32 application written in C++, with C# 6 it is now a .NET
        managed application written in C#. This rewrite was known as project "Roslyn" and the code is
        now open source and available on GitHub.


        Examples



        Operator nameof


        The nameof operator returns the name of a code element as a string. This is useful when throwing
        exceptions related to method arguments and also when implementing INotifyPropertyChanged.


         public string SayHello(string greeted)
         {
             if (greeted == null)
                 throw new ArgumentNullException(nameof(greeted));

             Console.WriteLine("Hello, " + greeted);
         }


        The nameof operator is evaluated at compile time and changes the expression into a string literal.
        This is also useful for strings that are named after their member that exposes them. Consider the
        following:


         public static class Strings
         {
             public const string Foo = nameof(Foo); // Rather than Foo = "Foo"
             public const string Bar = nameof(Bar); // Rather than Bar = "Bar"
         }


        Since nameof expressions are compile-time constants, they can be used in attributes, case labels,
        switch statements, and so on.




        https://riptutorial.com/                                                                             123
   172   173   174   175   176   177   178   179   180   181   182