typeof Operator Keyword in C#
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.
Important points:
- 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.
Syntax:
System.Type type = typeof(int);
Here, type is the type that is obtained.
Example :
CSharp
// C# program to illustrate the // concept of typeof operator using System; class GFG { // Here store Type as a field static Type a = typeof ( double ); // Main method static void Main() { // Display the type of a Console.WriteLine(a); // Display the value type Console.WriteLine( typeof ( int )); // Display the class type Console.WriteLine( typeof (Array)); // Display the value type Console.WriteLine( typeof ( char )); // Display the array reference type Console.WriteLine( typeof ( int [])); // Display the string reference type Console.WriteLine( typeof ( string )); } } |
Output
System.Double System.Int32 System.Array System.Char System.Int32[] System.String
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. |
Example:
CSharp
// C# program to illustrate the // difference between typeof // operator and GetType method using System; public class GFG { // Main method static public void Main() { string s = "Geeks" ; // using typeof operator Type a1 = typeof ( string ); // using GetType method Type a2 = s.GetType(); // checking for equality Console.WriteLine(a1 == a2); // taking a type object object obj = "Hello" ; // using typeof operator Type b1 = typeof ( object ); // using GetType method Type b2 = obj.GetType(); // checking for equality // it will return False as // GetType method is used // to obtain run-time type Console.WriteLine(b1 == b2); } } |
Output
True False
Output:
True False
Explanation: Here, 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.
Please Login to comment...