CodeBlanks Logo Icon CodeBlanks

The Type class

C# course · Advanced · Lesson 43/83

Learn to get a Type object with typeof and GetType.

The Type class

The Type class holds runtime information about a type. It is obtained in two main ways: typeof(MyClass) for types known at compile time, obj.GetType() for the runtime type of an instance.

typeof is an operator that takes a type name. GetType is a method called on an object. Both return a Type. From this object you can list methods, properties, fields and constructors; reflection starts here.

typeof vs GetType

typeof(T) works at compile time; T must be a constant type name. obj.GetType() returns the actual runtime type of any object — it is a virtual method.

When a base class reference holds a derived instance, GetType returns the derived type. E.g. for object o = "text";, o.GetType() returns String. typeof(object) always returns Object.

Exercise Print the type name of an integer

Define int x = 42;. Get its type with Type t = x.GetType();. Print t.Name with Console.WriteLine.

Show example solution
Get the type with Type t = x.GetType();. Print the name with Console.WriteLine(t.Name);.
Example solution:
using System;

class Program
{
    static void Main()
    {
        int x = 42;
        Type t = x.GetType();
        Console.WriteLine(t.Name);
    }
}

Test yourself

  1. What does obj.GetType() return?

    • The class name as a string
    • The runtime type of the object (Type)
    • The object's field names
    • The object's memory address
    Show answer

    The runtime type of the object (Type) — Correct. GetType returns the runtime type of the object as Type.

  2. Complete the typeof call

    Type t = ____(string);
    Show answer
    Type t = typeof(string);
  3. Match the expression to its behavior

    typeof(T)
    Compile time
    obj.GetType()
    Runtime
    typeof(int)
    For a primitive
    t.FullName
    Gives the full name

All lessons in Advanced