Partager via


Visual Basic Concepts

Discovering the Class an Object Belongs To

Generic object variables (that is, variables you declare As Object) can hold objects of many different classes. Similarly, variables declared with Visual Basic's built-in Form and Control types can contain forms and controls of different classes.

When using variables of these types, you may need to take different actions based on the class of an object — for example, some objects may not support a particular property or method. Visual Basic provides two ways to do this: the TypeOf keyword and the TypeName function.

The TypeOf keyword can only be used in If ... Then ... Else statements. You must include the class name directly in your code. For example, If TypeOf MyControl Is CheckBox Then.

The TypeName function is more flexible. You can use it anywhere in your code, and because it returns the class name as a string, you can compare it to the value in a string variable.