C# Reference ยท Operators and Expressions
The typeof operator
Reference for the C# typeof operator: get the System.Type for a compile-time known type, open generics, arrays and nested types, and compare it to GetType().
typeof(T) returns the System.Type object that describes the type T. You name the type in your source code, so the compiler knows it at build time. The result is the same object that reflection gives you at run time.
Use typeof when you need to ask about a type itself: its name, its members, its base type, or whether it matches the type of another value.
Type t = typeof(int); // System.Int32
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
typeof(type-name) typeof(unbound-generic-type) // typeof(List<>), typeof(Dictionary<,>) typeof(void)
| Name | Description |
|---|---|
type-name |
Any type that is known when you compile: built-in, user-defined, array, constructed generic, nullable or pointer type. |
unbound-generic-type |
A generic type with empty type-argument slots. One comma per extra type parameter. |
Returns: a System.Type. The same type always produces the same object, so == works to compare them.
Errors: you cannot pass a variable, a type parameter whose value is unknown, or an expression. typeof(T) inside a generic method is allowed and gives the type actually used by the caller.
Usage notes
typeof(Dog)is fixed at compile time.value.GetType()asks the object at run time. They are equal only when the object's exact type isDog.is AnimalandIsAssignableFromfollow inheritance.GetType() == typeof(Animal)is an exact match and ignores subclasses.typeof(int?)isNullable<int>. The runtime never keeps a boxed nullable: a boxedint?reportsintfromGetType().typeof(void)is allowed and givesSystem.Void, which is useful when you compare method return types.- Open generic types (
typeof(List<>)) cannot be instantiated until you callMakeGenericType. - In a generic method
typeof(T)is cheap. Comparing it with anothertypeofis optimized by the JIT, which is why you often seeif (typeof(T) == typeof(int))in performance-sensitive code. - Loading
Typeobjects is fast, but anything that follows (GetMethods,Activator) uses reflection and is much slower than a direct call. - For the sizes of unmanaged types see
sizeofon the typeof and sizeof page.