Object.GetType Method
Updated: December 2010
Gets the type of the current instance.
Assembly: mscorlib (in mscorlib.dll)
For two objects x and y that have identical runtime types, Object.ReferenceEquals(x.GetType(),y.GetType()) returns true. The following example uses the GetType method with the ReferenceEquals method to determine whether one numeric value is the same type as two other numeric values.
Dim n1 As Integer = 12 Dim n2 As Integer = 82 Dim n3 As Long = 12 Console.WriteLine("n1 and n2 are the same type: {0}", _ Object.ReferenceEquals(n1.GetType(), n2.GetType())) Console.WriteLine("n1 and n3 are the same type: {0}", _ Object.ReferenceEquals(n1.GetType(), n3.GetType())) ' The example displays the following output: ' n1 and n2 are the same type: True ' n1 and n3 are the same type: False
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.
The following example demonstrates that GetType returns the runtime type of the current instance.
Imports System ' Example base class and derived class. Note that it ' is not necessary to derive from Object explicitly; ' a class with no Inherits statement implicitly ' derives from Object. ' Public Class MyBaseClass Inherits Object End Class Public Class MyDerivedClass Inherits MyBaseClass End Class Public Class Test Public Shared Sub Main() Dim base As New MyBaseClass() Dim derived As New MyDerivedClass() Dim o As Object = derived Dim b As MyBaseClass = derived Console.WriteLine("base.GetType returns {0}", base.GetType()) Console.WriteLine("derived.GetType returns {0}", derived.GetType()) Console.WriteLine("Dim o As Object = derived; o.GetType returns {0}", o.GetType()) Console.WriteLine("Dim b As MyBaseClass = derived; b.Type returns {0}", b.GetType()) End Sub End Class 'This code example produces the following output: ' 'base.GetType returns MyBaseClass 'derived.GetType returns MyDerivedClass 'Dim o As Object = derived; o.GetType returns MyDerivedClass 'Dim b As MyBaseClass = derived; b.Type returns MyDerivedClass '
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Note: