Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Getting the one and only Type of an Object

, 7 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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#:
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:
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. Smile | :)

License

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

Share

About the Author

Sander Rossel
Software Developer
Netherlands Netherlands
Started programming in 2010 after completing a Bachelor Common Art and Cultural Sciences and a Master Media and Journalism. A decision I haven't come to regret!
A company hired me and they taught me the basics of VB.NET, WinForms and SQL Server.
 
At the end of that year I signed up for CodeProject and that was when my programming knowledge increased rapidly. Being around some of the best and most enthausiastic coders in the world certainly helps you develop your own skills.
 
After a while I enrolled in some IT courses at the Open University and I also got Microsoft Certified.
I am currently working to get a Bachelor degree in IT.
At my job I am programming in VB.NET, C# and SQL Server using WinForms and DevExpress controls.
 
Meanwhile I am trying to educate others through my (prize-winning) articles[^] here on CodeProject.

Comments and Discussions

 
QuestionGood PinmemberMember 103795027-Nov-13 5:05 
AnswerRe: Good PinmemberSander Rossel7-Nov-13 6:20 
GeneralRe: Here's another Tip/Trick... You can revote simply by voting ... PinmemberNaerling11-Oct-11 22:51 
GeneralRe: Now I feel bad about giving just 3. PinmemberKabwla.Phone11-Oct-11 22:40 
GeneralReason for my vote of 3 Pretty good information, though I do... PinmemberKabwla.Phone11-Oct-11 22:12 
GeneralRe: Although I respect your vote of 3 I cannot just let it pass.... PinmemberNaerling11-Oct-11 22:37 
GeneralYou could probably mention the Type.IsAssignableFrom method ... Pinmembermoozzyk10-Oct-11 19:49 
GeneralReason for my vote of 5 Excellent information PinmemberUSABebopKid7-Oct-11 9:18 
GeneralRe: Thanks, always good to hear! PinmemberNaerling7-Oct-11 12:41 
GeneralReason for my vote of 5 Good explanation of the differences PinmemberReiss6-Oct-11 21:44 
GeneralRe: Thanks! Glad you liked it :) PinmemberNaerling6-Oct-11 22:04 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 7 Oct 2011
Article Copyright 2011 by Sander Rossel
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid