TypeOf
How can we test the type of an Object instance in VB.NET? With the TypeOf
operator, we can access and test the type of a variable.
With the Is keyword, we can test for a specific type (like String
or a class
). And IsNot
tests that the type is not the specified one.
To begin, this VB.NET example program introduces a simple class
called Example. The Example class
derives from Object (as do all classes).
class
, and refer to it through a Object reference variable.TypeOf
operator along with the Is-keyword to test the the local variable is an instance of the Example class
.IsNot
operator performs the opposite check—it is a clear way to combine the "Not" and "Is" operators.TryCast
, we cast our Object local variable back into an Example reference.TypeOf
, all base classes of a variable are also checked, and this means the Is-keyword will return True for Object.Class Example Public Dim _name As String = "bird" End Class Module Module1 Sub Main() ' Part 1: refer to a new Example instance as an Object. Dim t As Object = New Example() ' Part 2: use Is-operator with TypeOf to test type. If TypeOf t Is Example Console.WriteLine("Is Example") End If ' Part 3: use IsNot operator with TypeOf. If TypeOf t IsNot String Console.WriteLine("IsNot String") End If ' Part 4: use TryCast to get back to Example type. Dim e = TryCast(t, Example) If Not IsNothing(e) Console.WriteLine($"Name = {e._name}") End If ' Part 5: TypeOf Is can detect base classes like Object. If TypeOf e Is Object Console.WriteLine("Is Object") End If End Sub End ModuleIs Example IsNot String Name = bird Is Object
Though we cannot use the Is-keyword to directly test the type of a variable, we can use it as part of a TypeOf
expression. This allows us to test types (and base types) in VB.NET.