Skip to content
Tutorials Center
My learning

Topics

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.

C#
Type t = typeof(int);   // System.Int32

Try it

C# Inspecting types

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.

C# typeof compared with GetType()

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

C#
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 is Dog.
  • is Animal and IsAssignableFrom follow inheritance. GetType() == typeof(Animal) is an exact match and ignores subclasses.
  • typeof(int?) is Nullable<int>. The runtime never keeps a boxed nullable: a boxed int? reports int from GetType().
  • typeof(void) is allowed and gives System.Void, which is useful when you compare method return types.
  • Open generic types (typeof(List<>)) cannot be instantiated until you call MakeGenericType.
  • In a generic method typeof(T) is cheap. Comparing it with another typeof is optimized by the JIT, which is why you often see if (typeof(T) == typeof(int)) in performance-sensitive code.
  • Loading Type objects 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 sizeof on the typeof and sizeof page.