Page 178 - CSharp/C#
P. 178

It is convenient to use nameof with Enums. Instead of:


         Console.WriteLine(Enum.One.ToString());


        it is possible to use:


         Console.WriteLine(nameof(Enum.One))


        The output will be One in both cases.




        The nameof operator can access non-static members using static-like syntax. Instead of doing:


         string foo = "Foo";
         string lengthName = nameof(foo.Length);


        Can be replaced with:


         string lengthName = nameof(string.Length);


        The output will be Length in both examples. However, the latter prevents the creation of
        unnecessary instances.



        Although the nameof operator works with most language constructs, there are some limitations. For
        example, you cannot use the nameof operator on open generic types or method return values:


         public static int Main()
         {
             Console.WriteLine(nameof(List<>)); // Compile-time error
             Console.WriteLine(nameof(Main())); // Compile-time error
         }


        Furthermore, if you apply it to a generic type, the generic type parameter will be ignored:


         Console.WriteLine(nameof(List<int>));  // "List"
         Console.WriteLine(nameof(List<bool>)); // "List"


        For more examples, see this topic dedicated to nameof.




        Workaround for previous versions (more


        detail)




        Although the nameof operator does not exist in C# for versions prior to 6.0, similar functionality can
        be had by using MemberExpression as in the following:

        6.0

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