본문 바로가기
프로그래밍/C#

C# nameof Expression

by bantomak 2023. 5. 26.
반응형

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
var 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
view raw nameof_1.cs hosted with ❤ by GitHub

 

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

 

public string Name
{
get => name;
set => name = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null");
}
view raw nameof_2.cs hosted with ❤ by GitHub

 

nameof() vs ToString()의 차이점

ToString()은 런타임에서 평가된다. 그리고 포멧 변경이 가능하다.

nameof()은 컴파일 타임에서 평가된다. 그래서 런타임에서 영향을 받지 않는다.

 

댓글