nameof expression (C# reference)

A nameof expression produces the name of a variable, type, or member as the string constant:

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List
Console.WriteLine(nameof(List<int>.Count));  // output: Count
Console.WriteLine(nameof(List<int>.Add));  // output: Add

var numbers = new List<int> { 1, 2, 3 };
Console.WriteLine(nameof(numbers));  // output: numbers
Console.WriteLine(nameof(numbers.Count));  // output: Count
Console.WriteLine(nameof(numbers.Add));  // output: Add

As the preceding example shows, in the case of a type and a namespace, the produced name is usually not fully qualified.

A nameof expression is evaluated at compile time and has no effect at run time.

You can use a nameof expression to make the argument-checking code more maintainable:

public string Name
{
    get => name;
    set => name = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null");
}

A nameof expression is available in C# 6 and later.

C# language specification

For more information, see the Nameof expressions section of the C# language specification.

See also