skip to content

Runtime Type Inspection

Type, typeof, GetType and BindingFlags expose members at run time, and Activator and MethodInfo.Invoke call them slowly. Interviewers ask about cost and trimming warnings.

on this pageshow

explore

questions

6

In C#, what do typeof(ICommand) and cmd.GetType() return when cmd is declared as ICommand but holds a DeployCommand?

level: juniorimportance: must knowfreq 62%

answer

  1. compile time vs run time
  2. declared type vs actual object
  3. operator on a name, method on an instance
  4. exact class, not "is a"

basics

~10 s

typeof(ICommand) is fixed at compile time from the type name and returns the Type for ICommand; cmd.GetType() runs on the object at run time and returns DeployCommand, its actual class.

solid answer

~30 s

`typeof(X)` takes a type name, so the compiler fixes the answer: `typeof(ICommand)` is always the `Type` for `ICommand`, and it needs no object. `GetType()` is a non-virtual method on `System.Object` that asks the object at run time, so `cmd.GetType()` returns `DeployCommand` whatever the variable is declared as. Comparing `cmd.GetType() == typeof(DeployCommand)` is an exact-type test that fails for a subclass, where `is` would pass. `GetType()` on a null reference throws `NullReferenceException`, and on an `int?` holding 5 it returns `Int32`, because the value is boxed first.

code

csharp · 22 lines
csharp
#:property PublishAot=false
ICommand cmd = new DeployCommand();

Console.WriteLine(typeof(ICommand).Name);                         // ICommand
Console.WriteLine(cmd.GetType().Name);                            // DeployCommand
Console.WriteLine(Describe(cmd));                                 // ICommand vs DeployCommand
Console.WriteLine(cmd.GetType() == typeof(DeployCommand));        // True
Console.WriteLine(new SubDeploy().GetType() == typeof(DeployCommand)); // False
Console.WriteLine(new SubDeploy() is DeployCommand);              // True

int? maybe = 5;
Console.WriteLine(maybe.GetType().Name);                          // Int32

ICommand? none = null;
try { Console.WriteLine(none!.GetType()); }
catch (NullReferenceException) { Console.WriteLine("NullReferenceException"); }

static string Describe<T>(T value) => $"{typeof(T).Name} vs {value!.GetType().Name}";

interface ICommand { void Execute(); }
class DeployCommand : ICommand { public void Execute() { } }
class SubDeploy : DeployCommand { }

go deeper

for a junior

Recall that typeof takes a type name and is decided at compile time, while GetType() asks the object at run time. Say what each returns for an interface-typed variable.

for a middle

Explain why GetType() == typeof(X) is an exact test that rejects subclasses, and when to use is or IsAssignableFrom instead. Mention the null and int? edge cases.

for a senior

Show where the choice breaks real code: a binder that reflects over typeof(T) and sees only interface members, or a registry keyed by exact type that rejects a subclass.

for a principal

Connect the choice to what tooling can see: a type named with typeof is visible to the trimmer, while a GetType() result is not, which shapes how a reflective library should be designed.

## Two ways to get a `Type` Every type the .NET runtime knows about is described by a `System.Type` object. C# gives you two everyday ways to get one, and they answer different questions. - **`typeof(X)`** is an operator whose operand is a *type name*. Which type it names is fixed when the code is compiled; no object is involved, so it works for interfaces, abstract classes, static classes and enums alike. `typeof(ICommand)` is always the `Type` for `ICommand`. - **`obj.GetType()`** is an instance method declared on `System.Object`. It runs when the program runs and asks the *object* what it really is. It is not virtual, so no class can override it to lie about its type. So for `ICommand cmd = new DeployCommand();` the two give different answers: `typeof(ICommand).Name` is `"ICommand"`, while `cmd.GetType().Name` is `"DeployCommand"`. The variable's **declared (static) type** is `ICommand`; the object's **run-time type** is `DeployCommand`. A CLI tool that discovers commands and copies options onto them needs the second, because the properties it wants live on the concrete class, not on the interface. | | `typeof(X)` | `obj.GetType()` | |---|---|---| | Input | a type name | an object reference | | Decided | at compile time (for a named type) | at run time | | Works on `null` | yes, no object needed | no, `NullReferenceException` | | Typical use | a known type: a dictionary key, a comparison target | what an object actually is | ## Generic code: `typeof(T)` is the type argument Inside a generic method, `typeof(T)` gives whatever type argument the call supplied. When the compiler *infers* that argument, it uses the static type of the expression at the call site. The snippet's `Describe<T>(T value)` called with the `ICommand` variable prints `ICommand vs DeployCommand`: `T` was inferred as `ICommand`, but the object is still a `DeployCommand`. That gap is a common source of reflection bugs, such as a serializer or option binder that reflects over `typeof(T)` and sees only the interface's members. (How generic type arguments themselves work belongs with the generics material.) ## Exact match vs "is a" `GetType()` returns the **exact** class, so comparing it with `==` is an exact-type test: 1. `cmd.GetType() == typeof(DeployCommand)` is `true` for a `DeployCommand`. 2. For `class SubDeploy : DeployCommand`, `new SubDeploy().GetType() == typeof(DeployCommand)` is `false`. 3. `new SubDeploy() is DeployCommand` is `true`, because `is` accepts derived types. Use `==` on `Type` objects when only that exact class may pass (a command registry keyed by concrete type, say); use `is`, `Type.IsAssignableTo` or `Type.IsAssignableFrom` when any subclass or implementer should pass. Picking `==` where the rule is "is a" quietly rejects every subclass. ## Edge cases interviewers probe - **Null references.** `GetType()` needs an object. Calling it through a null reference throws `NullReferenceException`; `typeof` never does, because it needs no instance. - **Nullable value types.** `int? maybe = 5; maybe.GetType()` returns the `Type` for `Int32`, not `Nullable<Int32>`. Calling `GetType()` boxes the value, and boxing a non-null `Nullable<T>` produces a boxed `T`. If `maybe` were null, the box would be null and the call would throw. - **Boxed values.** `object boxed = 42; boxed.GetType()` is `Int32`: the box remembers the value type it holds. - **The `Type` of a `Type`.** `typeof(ICommand).GetType()` names `RuntimeType`, the runtime's internal class behind `Type` objects. That is why "it returns RuntimeType" sometimes shows up as a wrong answer. ## Why it matters for reflection All the other reflection APIs, such as `GetProperties`, `GetMethod` and `Activator.CreateInstance`, start from a `Type`. Choosing the wrong one decides what they can find. Reflect over `typeof(ICommand)` and you see only the interface's members. Reflect over `cmd.GetType()` and you see the concrete class's public members, inherited ones included. When a binder copies `--region eu` onto a property called `Region` that exists only on `DeployCommand`, only the run-time type finds it. One trimming detail travels with this choice: when a tool removes unused code at publish, a `Type` that comes from `GetType()` carries no information about which members must be kept, and the trimming analysis warns about it. That story is told with the trimming warnings. A quick rule for choosing: 1. You need the members of whatever the object really is: call `obj.GetType()`, and guard against null first. 2. You need one fixed type, as a dictionary key, a registration or the right-hand side of a comparison: write `typeof(X)`. 3. You need "is this a `DeployCommand` or something derived from it": use `is`, `IsAssignableTo` or `IsAssignableFrom`, not `==`.

  • Inside `static void Log<T>(T item)`, why can `typeof(T)` and `item.GetType()` disagree?
    `typeof(T)` is the type argument the call supplied, and an inferred argument is the static type of the expression passed in. Called with a variable declared as `ICommand` that holds a `DeployCommand`, `T` is `ICommand` while `item.GetType()` is `DeployCommand`. Reflect over `item.GetType()` when you need the concrete class's members, and remember it throws on null.
  • How do you test whether an object is a `DeployCommand` or any subclass of it, using `Type` objects only?
    Use `typeof(DeployCommand).IsAssignableFrom(obj.GetType())`, or the newer spelling `obj.GetType().IsAssignableTo(typeof(DeployCommand))`. Both accept the class itself and anything derived from it, whereas `obj.GetType() == typeof(DeployCommand)` accepts only the exact class. With a typed object in hand, `obj is DeployCommand` is the plain way to say it.

A crate's manifest line says it holds tools (the declared type); opening the crate shows a cordless drill (the run-time type). typeof reads the manifest entry you name; GetType() opens the crate in front of you, and there is nothing to open when no crate is there.

  • typeof(cmd) on a variable returns the object's run-time type
  • cmd.GetType() returns the declared interface type ICommand
  • GetType() == typeof(Base) is true for derived classes
  • GetType() on an int? returns Nullable<Int32>
  • Classes can override GetType() to report another type
open as a page

In C#, how does a CLI tool find every ICommand class in its assembly and create each with Activator.CreateInstance, and what can fail?

level: middleimportance: should knowfreq 32%

basics

~10 s

Scan Assembly.GetTypes(), keep classes that are non-abstract and assignable to ICommand, then call Activator.CreateInstance(type). A missing parameterless constructor throws MissingMethodException; a constructor that throws arrives as TargetInvocationException.

open as a page

In C#, why does typeof(DeployOptions).GetProperty("verbose") return null for a public Verbose property, and which BindingFlags fix it?

level: middleimportance: should knowfreq 34%

basics

~10 s

Reflection matches member names case-sensitively, so "verbose" misses Verbose. Passing BindingFlags.IgnoreCase alone finds nothing either; the fix is Instance | Public | IgnoreCase.

open as a page

A C# CLI tool dispatches commands with MethodInfo.Invoke and its catch (CommandFailedException) never fires; why, and how does MethodInfo.CreateDelegate change that and the per-call cost?

level: seniorimportance: should knowfreq 30%

basics

~10 s

MethodInfo.Invoke wraps whatever the target throws in TargetInvocationException, and boxes arguments and results on every call. A delegate from CreateDelegate<TDelegate>(), created once and cached, makes a typed call that throws unwrapped and allocates nothing.

open as a page

A C# CLI tool built with PublishAot reports IL2026, IL2070, IL2075 and IL3050 on its reflection code; what does each mean, and how does [DynamicallyAccessedMembers] fix some?

level: seniorimportance: should knowfreq 26%

basics

~10 s

IL2026 and IL3050 flag calls to members marked [RequiresUnreferencedCode] or [RequiresDynamicCode]. IL2070 and IL2075 flag an unannotated Type reaching reflection; [DynamicallyAccessedMembers] on that Type keeps the named members and clears them.

open as a page

In .NET 8 and later, how does [UnsafeAccessor] let C# code read and write a private field like OptionParser._seen, and how does it differ from FieldInfo.SetValue?

level: seniorimportance: nice to knowfreq 12%

basics

~10 s

You declare a static extern method marked [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_seen")] that takes an OptionParser and returns ref int; the runtime binds it to the field, with no reflection lookup, boxing or Type object.

open as a page