System.Object.GetType Method

Gets the Type of the current instance.

Syntax

public Type GetType ()

Returns

The exact runtime type of the current instance.

Remarks

For two objects x and y that have identical runtime types, Object.ReferenceEquals(x.GetType(),y.GetType()) returns true. The following example uses the object.GetType method with the object.ReferenceEquals(object, object) method to determine whether one numeric value is the same type as two other numeric values.

code reference: System.Object.GetType#1

Note:

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. For example, you can use the TypeOf…Is construct in Visual Basic or the is keyword in C#.

The Type object exposes the metadata associated with the class of the current object.

Example

The following example demonstrates the fact that object.GetType returns the run-time type of the current instance:

C# Example

using System;
public class MyBaseClass: Object {
}
public class MyDerivedClass: MyBaseClass {
}
public class Test {
   public static void Main() {
   MyBaseClass myBase = new MyBaseClass();
   MyDerivedClass myDerived = new MyDerivedClass();

   object o = myDerived;
   MyBaseClass b = myDerived;

   Console.WriteLine("mybase: Type is {0}", myBase.GetType());
   Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
   Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
   Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
   }
}

The output is

mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0