Click here to Skip to main content
15,850,917 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Getting the one and only Type of an Object

Rate me:
Please Sign up or sign in to vote.
4.85/5 (6 votes)
7 Oct 2011CPOL1 min read 23.4K   5   11
How to check an Objects Type, ignoring all subtypes, in C# and VB.
Last week, I had a problem with types and derived types. I wanted to execute some code when a type of SomeButton was clicked. Unfortunately, the piece of code was pretty generic and basically any type of Object could pass my piece of code. The result was that my code did not only execute when SomeButton was clicked, but also when any derived Class of SomeButton was clicked. That was when I learned the subtle difference between instance is Type (C#), TypeOf instance Is Type (VB) and GetType. Below is the code for both C# and VB to check the exact Type of an Object.
This is a Console Application, so you can simply copy/paste the complete example into a new Console Application Project and see the differences for yourself.

C#:
C#
using System;

namespace TypeTipCSharp
{
	class Base { }
	class Derived : Base { }

	class Program
	{
		static void Main(string[] args)
		{
			Derived d = new Derived();
			Console.WriteLine("Variable d is an instance of Derived, which inherits from Base.");

			if (d is Base)
			{ Console.WriteLine("The type of d is Base"); }
			else
			{ Console.WriteLine("The type of d is not Base"); }

			if (d.GetType() == typeof(Base))
			{ Console.WriteLine("The GetType of d is Base"); }
			else
			{ Console.WriteLine("The GetType of d is not Base"); }

			Base b = new Derived();
			Console.WriteLine("{0}Variable b is of Type Base, but has an instance of Derived assigned to it.", Environment.NewLine);

			if (b is Base)
			{ Console.WriteLine("The type of b is Base"); }
			else
			{ Console.WriteLine("The type of b is not Base"); }

			if (b.GetType() == typeof(Base))
			{ Console.WriteLine("The GetType of b is Base"); }
			else
			{ Console.WriteLine("The GetType of b is not Base"); }

			if (b is Derived)
			{ Console.WriteLine("The type of b is Derived"); }
			else
			{ Console.WriteLine("The type of b is not Derived"); }

			if (b.GetType() == typeof(Derived))
			{ Console.WriteLine("The GetType of b is Derived"); }
			else
			{ Console.WriteLine("The GetType of b is not Derived"); }

			Console.WriteLine("{0}Press a key to close.", Environment.NewLine);
			Console.ReadKey();

		}
	}
}


VB:
VB
Public Class Base
End Class

Public Class Derived
	Inherits Base
End Class

Module Module1

	Sub Main()
		Dim d As New Derived
		Console.WriteLine("Variable d is an instance of Derived, which inherits from Base.")

		If TypeOf d Is Base Then
			Console.WriteLine("The type of d is Base")
		Else
			Console.WriteLine("The type of d is not Base")
		End If

		If d.GetType = GetType(Base) Then
			Console.WriteLine("The GetType of d is Base")
		Else
			Console.WriteLine("The GetType of d is not Base")
		End If

		Dim b As Base = New Derived
		Console.WriteLine("{0}Variable b is of Type Base, but has an instance of Derived assigned to it.", Environment.NewLine)

		If TypeOf b Is Base Then
			Console.WriteLine("The type of b is Base")
		Else
			Console.WriteLine("The type of b is not Base")
		End If

		If b.GetType = GetType(Base) Then
			Console.WriteLine("The GetType of b is Base")
		Else
			Console.WriteLine("The GetType of b is not Base")
		End If

		If TypeOf b Is Derived Then
			Console.WriteLine("The type of b is Derived")
		Else
			Console.WriteLine("The type of b is not Derived")
		End If

		If b.GetType = GetType(Derived) Then
			Console.WriteLine("The GetType of b is Derived")
		Else
			Console.WriteLine("The GetType of b is not Derived")
		End If

		Console.WriteLine("{0}Press a key to close.", Environment.NewLine)
		Console.ReadKey()
	End Sub

End Module


The result:
Variable d is an instance of Derived, which inherits from Base.
The type of d is Base
The GetType of d is not Base

Variable b is of Type Base, but has an instance of Derived assigned to it.
The type of b is Base
The GetType of b is not Base
The type of b is Derived
The GetType of b is Derived


So GetType will always return the exact type of an Object which can be compared to a Type. Only when the two types have an exact match do they really match. As you can see, Derived is a type of Base, but Derived.GetType does not match Base.
instance is Type and TypeOf instance Is Type return True whenever the instance is of the type Type or any derived type!
The difference is subtle, but very important. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO JUUN Software
Netherlands Netherlands
Sander Rossel is a Microsoft certified professional developer with experience and expertise in .NET and .NET Core (C#, ASP.NET, and Entity Framework), SQL Server, Azure, Azure DevOps, JavaScript, MongoDB, and other technologies.

He is the owner of JUUN Software, a company specializing in custom software. JUUN Software uses modern, but proven technologies, such as .NET Core, Azure and Azure DevOps.

You can't miss his books on Amazon and his free e-books on Syncfusion!

He wrote a JavaScript LINQ library, arrgh.js (works in IE8+, Edge, Firefox, Chrome, and probably everything else).

Check out his prize-winning articles on CodeProject as well!

Comments and Discussions

 
QuestionGood Pin
Member 103795027-Nov-13 6:05
Member 103795027-Nov-13 6:05 
AnswerRe: Good Pin
Sander Rossel7-Nov-13 7:20
professionalSander Rossel7-Nov-13 7:20 
GeneralRe: Here's another Tip/Trick... You can revote simply by voting ... Pin
Sander Rossel11-Oct-11 23:51
professionalSander Rossel11-Oct-11 23:51 
GeneralRe: Now I feel bad about giving just 3. Pin
Kabwla.Phone11-Oct-11 23:40
Kabwla.Phone11-Oct-11 23:40 
GeneralReason for my vote of 3 Pretty good information, though I do... Pin
Kabwla.Phone11-Oct-11 23:12
Kabwla.Phone11-Oct-11 23:12 
GeneralRe: Although I respect your vote of 3 I cannot just let it pass.... Pin
Sander Rossel11-Oct-11 23:37
professionalSander Rossel11-Oct-11 23:37 
GeneralYou could probably mention the Type.IsAssignableFrom method ... Pin
moozzyk10-Oct-11 20:49
moozzyk10-Oct-11 20:49 
GeneralReason for my vote of 5 Excellent information Pin
ARBebopKid7-Oct-11 10:18
ARBebopKid7-Oct-11 10:18 
GeneralRe: Thanks, always good to hear! Pin
Sander Rossel7-Oct-11 13:41
professionalSander Rossel7-Oct-11 13:41 
Thanks, always good to hear!
GeneralReason for my vote of 5 Good explanation of the differences Pin
Reiss6-Oct-11 22:44
professionalReiss6-Oct-11 22:44 
GeneralRe: Thanks! Glad you liked it :) Pin
Sander Rossel6-Oct-11 23:04
professionalSander Rossel6-Oct-11 23:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.