C# nameof Operator

C# nameof Operator

C# nameof operator returns the name of any symbol, such as type, member, variable etc., as a string.

int count = 123;
string name = nameof (count); // name is "count"

To get 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":

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

C# nameof operator Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = nameof(StringBuilder.Length);
           
            Console.WriteLine(name);
            Console.ReadLine();
        }
    }
}

Output:

C# nameof operator Example