Home
VB.NET
TypeOf Use (Is, IsNot)
Updated Sep 5, 2024
Dot Net Perls
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.
Object
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.
Class
CType
Example. To begin, this VB.NET example program introduces a simple class called Example. The Example class derives from Object (as do all classes).
Part 1 We create an instance of the Example class, and refer to it through a Object reference variable.
Part 2 We use the TypeOf operator along with the Is-keyword to test the the local variable is an instance of the Example class.
Part 3 The IsNot operator performs the opposite check—it is a clear way to combine the "Not" and "Is" operators.
IsNot, Is
Part 4 With TryCast, we cast our Object local variable back into an Example reference.
TryCast
Part 5 With 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 Module
Is Example IsNot String Name = bird Is Object
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 5, 2024 (edit link).
Home
Changes
© 2007-2025 Sam Allen