nameof 식(C# 참조)

nameof 식은 변수, 형식 또는 멤버의 이름을 문자열 상수로 생성합니다. nameof 식은 컴파일 시간에 계산되며 런타임에는 영향을 주지 않습니다. 피연산자는 형식 또는 네임스페이스인 경우 생성된 이름이 정규화되지 않습니다. 다음 예제에서는 nameof 식의 사용을 보여줍니다.

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List
Console.WriteLine(nameof(List<int>.Count));  // output: Count
Console.WriteLine(nameof(List<int>.Add));  // output: Add

List<int> numbers = new List<int>() { 1, 2, 3 };
Console.WriteLine(nameof(numbers));  // output: numbers
Console.WriteLine(nameof(numbers.Count));  // output: Count
Console.WriteLine(nameof(numbers.Add));  // output: Add

nameof 식을 사용하여 인수 검사 코드를 더 쉽게 유지 관리할 수 있습니다.

public string Name
{
    get => name;
    set => name = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null");
}

C# 11부터 메서드 또는 해당 매개 변수에 대한 특성 내에서 메서드 매개 변수와 함께 nameof 식을 사용할 수 있습니다. 다음 코드는 메서드의 특성, 로컬 함수 및 람다 식의 매개 변수에 대해 이 작업을 수행하는 방법을 보여줍니다.

[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();
}

매개 변수가 있는 nameof 식은 null 허용 분석 특성 또는 CallerArgumentExpression 특성을 사용할 때 유용합니다.

피연산자가 축자 식별자인 경우 다음 예제와 같이 @ 문자는 이름의 일부가 아닙니다.

var @new = 5;
Console.WriteLine(nameof(@new));  // output: new

C# 언어 사양

자세한 내용은 C# 언어 사양Nameof 식섹션 및 C# 11 - 확장 nameof 범위 기능 사양을 참조하세요.

참고 항목