The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the
System.Type object for a type. This operator takes the Type itself as an argument and returns the marked type of the argument.
- The operand of typeof operator is always a type of parameter or name of the type. It does not contain variable.
- It is not allowed to overload typeof operator.
- It is allowed to use typeof operator on open generic types.
- It is allowed to use typeof operator on bounded or unbounded types.
System.Type type = typeof(int);
Here, type is the type that is obtained.
System.Double System.Int32 System.Array System.Char System.Int32
Difference between typeof operator and GetType method
|typeof Operator||GetType Method|
|It takes the Type itself as an argument and returns the marked type of the argument.||It only invoked on the instance of the type.|
|It is used to get a type that is known at compile-time.||It is used to obtain the type of an object at run-time.|
|It cannot be used on an instance.||It can be used on instance.|
Type b1 = typeof(object); this will return System.Object but
Type b2 = obj.GetType(); will return System.String. As, at compile time only object type reference is created, but at runtime the string(“Hello”) is actually storing in it.