08 Feb 2024




Beginner

In C#, typeof and GetType() are used to obtain type information, but they are used in slightly different contexts:

  1. typeof:
    • typeof is an operator in C# that returns a Type object representing the type of a specified type name. It is evaluated at compile-time.
    • It is typically used when you have the name of a type available at compile-time and you want to get information about that type.
    • Example:
// Example using typeof
   Type type = typeof(int);
   // type now holds the Type object for the int type
  1. GetType():
    • GetType() is a method defined in the System.Object class in C#. It returns the Type of the current instance.
    • It is used when you have an instance of an object at runtime and you want to get information about its type dynamically.
    • Example:
 // Example using GetType()
object obj = new MyClass();
Type type = obj.GetType();
// type now holds the Type object for the actual type of the 'obj' instance (e.g., MyClass)

In summary, typeof is used to get type information at compile-time, while GetType() is used to get type information at runtime for a specific instance of an object.

c-sharp
typeof
gettype
difference