08 Feb 2024
Beginner
In C#, typeof and GetType() are used to obtain type information, but they are used in slightly different contexts:
- typeof:
typeofis an operator in C# that returns aTypeobject 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
- GetType():
GetType()is a method defined in theSystem.Objectclass in C#. It returns theTypeof 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.