0
0
CsharpHow-ToBeginner · 3 min read

How to Get Type at Runtime in C# - Simple Guide

In C#, you can get the type of an object at runtime using the GetType() method. This method returns a Type object that describes the exact type of the instance it is called on.
📐

Syntax

The GetType() method is called on an instance of any object to get its runtime type. It returns a Type object that contains information about the object's type.

  • objectInstance.GetType(): Calls the method on the object instance.
  • Type: The return type representing the type information.
csharp
Type typeInfo = objectInstance.GetType();
💻

Example

This example shows how to get the runtime type of different objects and print their names.

csharp
using System;

class Program
{
    static void Main()
    {
        int number = 42;
        string text = "hello";
        DateTime now = DateTime.Now;

        Console.WriteLine(number.GetType()); // System.Int32
        Console.WriteLine(text.GetType());   // System.String
        Console.WriteLine(now.GetType());    // System.DateTime
    }
}
Output
System.Int32 System.String System.DateTime
⚠️

Common Pitfalls

One common mistake is trying to use typeof() on an instance, which is incorrect because typeof() requires a type name, not an object. Another pitfall is assuming GetType() returns the compile-time type; it actually returns the runtime type, which can differ if you use inheritance.

csharp
/* Wrong way - causes compile error */
// var typeInfo = typeof(objectInstance); // Error: 'objectInstance' is a variable, not a type

/* Correct way */
var typeInfo = objectInstance.GetType();
📊

Quick Reference

Remember these key points when getting type at runtime in C#:

  • Use instance.GetType() to get the runtime type.
  • typeof(TypeName) is for compile-time type references.
  • GetType() returns a Type object with type details.
  • Runtime type can differ from compile-time type due to inheritance.

Key Takeaways

Use the GetType() method on an object instance to get its runtime type.
GetType() returns a Type object describing the exact type of the instance.
typeof() is used with type names, not object instances.
Runtime type may differ from compile-time type when inheritance is involved.
Always call GetType() on the instance, not on the class name.