Typeof operator
Peponi │ 1/2/2025 │ 2m
C#
SyntaxOperatortypeof
Typeof operator
1/2/2025
2m
Peponi
C#
SyntaxOperatortypeof
1. Introduction
typeof
연산자는 지정된 형식의 System.Type 인스턴스를 반환한다. typeof
의 인수는 형식 또는 형식 매개 변수의 이름으로, 제네릭 형식 또한 사용 가능하다.
typeof
에는 다음 형식을 사용할 수 없다.
2. Example
다음은 typeof
연산자를 통해 System.Type
인스턴스를 얻는 예시다.
Console.WriteLine(typeof(int));
Console.WriteLine(typeof(string));
Console.WriteLine(typeof(Dictionary<int, string>));
Console.WriteLine(typeof(Dictionary<, >));
/* output:
System.Int32
System.String
System.Collections.Generic.Dictionary`2[System.Int32,System.String]
System.Collections.Generic.Dictionary`2[TKey,TValue]
*/
typeof
연산자를 이용하여 형식 확인을 하는 경우 런타임 형식의 정확한 일치 여부를 파악할 수 있다. is 연산자와는 달리 정확히 동일한 형식일 때만 true
를 반환한다.
public class Base { }
public class Derived : Base { }
var foo = new Derived();
Console.WriteLine(foo is Base);
Console.WriteLine(foo is Derived);
Console.WriteLine(foo.GetType() == typeof(Base));
Console.WriteLine(foo.GetType() == typeof(Derived));
/* output:
True
True
False
True
*/
typeof
의 인수로는 식을 사용할 수 없다. 식의 런타임 형식을 얻으려는 경우, Object.GetType을 이용하여 얻을 수 있다.
//Console.WriteLine(typeof(1 + 1)); // 불가
Console.WriteLine((1 + 1.234).GetType());
var foo = new List<int>();
Console.WriteLine(foo.GetType());
/* output:
System.Double
System.Collections.Generic.List`1[System.Int32]
*/