CSharp - GetType Method and typeof Operator

Introduction

All types in C# are instance of System.Type.

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

  • Use GetType() method.
  • Use typeof operator on a type name.

GetType is evaluated at runtime.

typeof is evaluated at compile time.

System.Type has properties such as the type's name, assembly, base type, and so on. For example:

Demo

using System;

class Point { //from  ww w .j  a  v  a 2  s. c o  m
  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
         
     }
}

Result