C# 14 - (4) 형식 인자가 없는 제네릭 타입의 nameof 지원
이번 C# 신규 문법은 쉬어가는 코너가 되겠군요. ^^
Unbound generic types and nameof
; https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14#unbound-generic-types-and-nameof
[Proposal]: Unbound generic types in nameof #8480
; https://github.com/dotnet/csharplang/issues/8480
말 그대로, 형식 인자를 제공하지 않은 제네릭 타입에 대해서도 nameof 구문을 적용할 수 있게 바뀌었습니다.
// 반드시 형식 인자를 제공했지만,
string text = nameof(List<string>);
Console.WriteLine(text); // 출력 결과: List
// C# 14부터 형식 인자를 생략하는 것도 가능
text = nameof(List<>);
Console.WriteLine(text); // 출력 결과: List
// 참고로 기존의 typeof도 형식 인자를 생략할 수 있었습니다.
var unboundType = typeof(List<>); // C# 13 이전에도 가능
개인적으로 처음 저걸 봤을 때는 쓸 상황이 얼마나 될까 싶었는데요, 문서를 읽어 보니 납득이 되는 부분이 좀 있습니다. ^^
Unbound generic types in nameof
; https://github.com/dotnet/csharplang/blob/main/proposals/unbound-generic-types-in-nameof.md
비단, 저 타입 자체의 이름을 가져와야 하는 경우로 한정 짓는다면 그다지 유용하지 않을 수도 있지만, 그 범위가 해당 제네릭 타입의 멤버까지도 넓어진다면 얘기가 살짝 달라집니다.
string text = nameof(Stack<>.Push); // 출력 결과: Push
Console.WriteLine(text);
public class Stack<T>
{
public void Push(T item) { }
}
재미있는 건, 저 구문 자체가 nameof 내에서만 유효하다는 점입니다. 가령, 아래와 같은 코드는 컴파일 오류가 발생합니다.
// error CS0305: Using the generic type 'Stack<T>' requires 1 type arguments
var v = Stack<>.Push;
// typeof도 unbound 제네릭 타입의 멤버까지 지정하는 구문은 지원하지 않습니다.
var unboundMethod = typeof(Stack<>.Push); // error CS0426: The type name 'Push' does not exist in the type 'Stack<T>'
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]