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:
The preceding example using List<> is supported in C# 14 and later. You can use a nameof expression to make the argument-checking code more maintainable:
C#
publicstring Name
{
get => name;
set => name = value ?? thrownew ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null");
}
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:
C#
[ParameterString(nameof(msg))]
publicstaticvoidMethod(string msg)
{
[ParameterString(nameof(T))]
void LocalFunction<T>(T param) { }
var lambdaExpression = ([ParameterString(nameof(aNumber))] int aNumber) => aNumber.ToString();
}
Liity tapaamissarjaan ja luo skaalattavia tekoälyratkaisuja, jotka perustuvat reaalimaailman käyttötapauksiin muiden kehittäjien ja asiantuntijoiden kanssa.