Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

nameof expression (C# reference)

  • 2025-02-25
Feedback

In this article

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

C# language specification

For more information, see theNameof expressions section of theC# language specification, and theC# 11 - Extendednameof scope feature specification.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo