C# Interview Question #110

What is the difference between typeof, GetType(), and is?

Types, Equality, Immutability & Internals Senior Advanced

Quick Interview Answer

typeof obtains a Type object for a type known at compile time. GetType() obtains the actual runtime type of an object instance. The is operator tests whether an object is compatible with a specified type or pattern.

Detailed Explanation

typeof obtains a Type object for a type known at compile time. GetType() obtains the actual runtime type of an object instance. The is operator tests whether an object is compatible with a specified type or pattern.

typeof does not require an object instance. GetType requires a non-null object. is is normally preferred when the goal is safe type checking and optional extraction rather than metadata inspection.

Code Example

Type declaredType = typeof(Product);

object obj = new Product();
Type runtimeType = obj.GetType();

if (obj is Product product)
{
    Console.WriteLine(product.Id);
}