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
using System;
class GFG {
static Type a = typeof ( double );
static void Main()
{
Console.WriteLine(a);
Console.WriteLine( typeof ( int ));
Console.WriteLine( typeof (Array));
Console.WriteLine( typeof ( char ));
Console.WriteLine( typeof ( int []));
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
using System;
public class GFG {
static public void Main()
{
string s = "Geeks" ;
Type a1 = typeof ( string );
Type a2 = s.GetType();
Console.WriteLine(a1 == a2);
object obj = "Hello" ;
Type b1 = typeof ( object );
Type b2 = obj.GetType();
Console.WriteLine(b1 == b2);
}
}
|
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.
Last Updated :
11 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...