How to use typeof operator in C#
Description
GetType
does the runtime check
while the typeof
operator does
the compile-time check.
Syntax
The typeof operator has this general form:
typeof(type)
type
is the type being obtained.
Both GetType
and typeof
return System.Type
.
Example
Example for typeof operator
using System;//from w ww. j ava 2 s. co m
public class Point { public int X, Y; }
class Test
{
static void Main()
{
Point p = new Point();
Console.WriteLine(p.GetType().Name); // Point
Console.WriteLine(typeof(Point).Name); // Point
Console.WriteLine(p.GetType() == typeof(Point)); // True
Console.WriteLine(p.X.GetType().Name); // Int32
Console.WriteLine(p.Y.GetType().FullName); // System.Int32
}
}
The output:
Example 2
Get Type from typeof operator
using System; //from www . j ava 2s .com
using System.IO;
class MainClass {
public static void Main() {
Type t = typeof(StreamReader);
Console.WriteLine(t.FullName);
if(t.IsClass)
Console.WriteLine("Is a class.");
if(t.IsAbstract)
Console.WriteLine("Is abstract.");
else
Console.WriteLine("Is concrete.");
}
}
The code above generates the following result.