Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Operators and Expressions

The nameof operator

The C# nameof operator as an expression: what it accepts, how it works in attributes, logging and property notifications, and its C# 14 unbound generics.

nameof is an operator that turns a program element into its simple name, as a string. The compiler computes the text while compiling, so there is no run-time cost and the value is a constant. This page covers how it behaves as an expression; the keyword page explains the basics.

Because the name comes from a real symbol, renaming the symbol updates every nameof use, and a misspelled name fails to compile.

C#
string name = nameof(Customer.Email);   // "Email"

Try it

C# nameof as a constant in attributes and switches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# What nameof returns for different expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
nameof(named-entity)
Name Description
named-entity A local, parameter, field, property, method group, event, type, type parameter, namespace or enum member, possibly qualified.

Returns: a constant string containing the last identifier.

Errors: an unknown name gives CS0103; an expression that is not a name (a literal or a call result) is rejected.

Usage notes

  • It is a constant expression. You can use it in const string fields, case labels, default parameter values and attribute arguments.
  • Qualified names return only the final part: nameof(System.Text) is "Text".
  • Generic arguments are dropped: nameof(List<int>) is "List". C# 14 also accepts an unbound generic type, nameof(List<>).
  • Inside a type you can refer to an instance member without an instance, for example nameof(Title) in a property setter.
  • Method groups are accepted. Overloads do not matter, since only the name is used.
  • Verbatim identifiers lose the @: nameof(@class) is "class".
  • The operand is never evaluated, so null references and disabled code paths do not matter.
  • Typical uses: argument exceptions, INotifyPropertyChanged, logging templates, switch on member names, and [CallerArgumentExpression(nameof(arg))].
  • It cannot tell you the runtime type or the full path of something. For a type's full name use typeof(T).FullName.