Skip to content

Latest commit

 

History

History
40 lines (26 loc) · 2.51 KB

File metadata and controls

40 lines (26 loc) · 2.51 KB
title description ms.date f1_keywords helpviewer_keywords
The nameof expression - evaluate the text name of a symbol
The C# `nameof` expression produces the name of its operand. You use it whenever you need to use the name of a symbol as text
11/28/2022
nameof_CSharpKeyword
nameof
nameof expression [C#]

nameof expression (C# reference)

A nameof expression produces the name of a variable, type, or member as the string constant. A nameof 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't fully qualified. The following example shows the use of a nameof expression:

[!code-csharp-interactivenameof expression]

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

[!code-csharpnameof and argument check]

Beginning with C# 11, you can use a nameof expression with a method parameter inside an attribute 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:

:::code language="csharp" source="snippets/shared/NameOfOperator.cs" id="SnippetNameOfParameter":::

A nameof expression with a parameter is useful when you use the nullable analysis attributes or the CallerArgumentExpression attribute.

When the operand is a verbatim identifier, the @ character isn't the part of a name, as the following example shows:

[!code-csharp-interactivenameof verbatim]

C# language specification

For more information, see the Nameof expressions section of the C# language specification, and the C# 11 - Extended nameof scope feature specification.

See also