3.11. Test an Object's Type

Problem

You need to test the type of an object.

Solution

Use the inherited Object.GetType method to obtain a Type for the object. You can also use the TypeOf and Is operators to test an object's type.

How It Works

All types inherit the GetType method from the Object base class. As discussed in recipe 3-10, this method returns a Type reference representing the type of the object. The runtime maintains a single instance of Type for each type loaded, and all references for this type refer to this same object. This means you can compare two type references efficiently. For convenience, VB .NET provides the Is operator as a quick way to check whether an object is a specified type. In addition, Is will return True if the ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.