CSharp/C# Tutorial - C# GetType and typeof






All types in C# are represented at runtime with an instance of System.Type.

There are two basic ways to get a System.Type object:

  • Call GetType on the instance.
  • Use the typeof operator on a type name.

GetType is evaluated at runtime; typeof is evaluated statically at compile time.

System.Type has properties for such things as the type's name, assembly, base type, and so on.





Example

For example:

using System; 

class Point { 
   public int X, Y; 
} 

class Main { 
   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
   } 
} 




Example 2

The following code gets type from var defined variables.


using System; //from  w  w  w  .j av a  2s .c o  m

class Program { 
  static void Main(string[] args) { 
    var name = "java2s.com"; 
    var age = 25; 
    var isRabbit = true; 

    Type nameType = name.GetType(); 
    Type ageType = age.GetType(); 
    Type isRabbitType = isRabbit.GetType(); 

    Console.WriteLine("name is type " + nameType.ToString()); 
    Console.WriteLine("age is type " + ageType.ToString()); 
    Console.WriteLine("isRabbit is type " + isRabbitType.ToString()); 
  } 
}