This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Anameof
expression produces the name of a variable, type, or member as the string constant. Anameof
expression is evaluated at compile time and has no effect at run time. When the operand is a type or a namespace, the produced name isn'tfully qualified. The following example shows the use of anameof
expression:
Console.WriteLine(nameof(System.Collections.Generic)); // output: GenericConsole.WriteLine(nameof(List<int>)); // output: ListConsole.WriteLine(nameof(List<>)); // output: ListConsole.WriteLine(nameof(List<int>.Count)); // output: CountConsole.WriteLine(nameof(List<int>.Add)); // output: AddList<int> numbers = new List<int>() { 1, 2, 3 };Console.WriteLine(nameof(numbers)); // output: numbersConsole.WriteLine(nameof(numbers.Count)); // output: CountConsole.WriteLine(nameof(numbers.Add)); // output: Add
The preceding example usingList<>
is supported in C# 14 and later. You can use anameof
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");}
Beginning with C# 11, you can use anameof
expression with a method parameter inside anattribute on a method or its parameter. The following code shows how to do that for an attribute on a method, a local function, and the parameter of a lambda expression:
[ParameterString(nameof(msg))]public static void Method(string msg){ [ParameterString(nameof(T))] void LocalFunction<T>(T param) { } var lambdaExpression = ([ParameterString(nameof(aNumber))] int aNumber) => aNumber.ToString();}
Anameof
expression with a parameter is useful when you use thenullable analysis attributes or theCallerArgumentExpression attribute.
When the operand is averbatim identifier, the@
character isn't part of the name, as the following example shows:
var @new = 5;Console.WriteLine(nameof(@new)); // output: new
For more information, see theNameof expressions section of theC# language specification, and theC# 11 - Extendednameof
scope feature specification.
Was this page helpful?
Was this page helpful?