Typeof() vs GetType() in C#

CsharpProgrammingServer Side Programming

Typeof()

The type takes the Type and returns the Type of the argument.

For example: System.Byte for the following −

typeof(byte)

The following is an example −

Example

 Live Demo

using System;
class Program {
   static void Main() {
      Console.WriteLine(typeof(int));
      Console.WriteLine(typeof(byte));
   }
}

Output

System.Int32
System.Byte

GetType()

The GetType() method of array class in C# gets the Type of the current instance.

To get the type.

Type tp = value.GetType();

In the below example, we are checking the int value using the type.

if (tp.Equals(typeof(int)))
Console.WriteLine("{0} is an integer data type.", value)

The following is the usage of GetType() method in C#.

Example

 Live Demo

using System;

class Program {
   public static void Main() {
      object[] values = { (int) 100, (long) 17111};
      foreach (var value in values) {

         Type tp = value.GetType();

         if (tp.Equals(typeof(int)))
         Console.WriteLine("{0} is an integer data type.", value);

         else
         Console.WriteLine("'{0}' is not an int data type.", value);
      }
   }
}

Output

100 is an integer data type.
'17111' is not an int data type.
raja
Published on 16-Aug-2018 09:24:59
Advertisements