The nameof operator - CSharp Custom Type

CSharp examples for Custom Type:nameof

Introduction

The nameof operator returns the name of any symbol (type, member, variable, and so on) as a string:

Demo Code

using System;/*from  w  w w  .  j ava2 s  .  c om*/
class Test
{
   static void Main(){
      int count = 123;
      string name = nameof (count);       // name is "count"
      Console.WriteLine(name);
   }
}

Result

To specify the name of a type member such as a field or property, include the type as well.

This works with both static and instance members:

string name = nameof (StringBuilder.Length);

This evaluates to "Length".

To return "StringBuilder.Length", you would do this:

nameof (StringBuilder) + "." + nameof (StringBuilder.Length);

Related Tutorials