VB.NET VarType Function (VariantType Enum)Use the VarType built-in Function and the VariantType Enum.
determines the type of a variable in VB.NET. This variable could be of type Object or a more derived type. With the VarType function and the VariantType enumeration, we test the type of variables such as Integer types.Integer
First, this program uses a Dim of type Integer. It then calls VarType on this variable. We print the String representation of the VariantType result. We show the GetType function, which is separate.
Finally: We test the VariantType variable in an If-statement. We display a helpful message.
VB.NET program that uses VarType function
Dim value As Integer = 5
' Get VarType.
Dim type As VariantType = VarType(value)
' Write string representation.
' Show GetType method.
' You can check the VariantType against constants.
If type = VariantType.Integer Then
Console.WriteLine("It's an integer!")
It's an integer!
Change. What happens if you change the "Dim value As Integer" line to "Dim value As String"? The result of the program will be different. Also, the If-statement will not evaluate to True and the final line will not be printed to the output.
Changed line in program: VB.NET
Dim value As String = "cat"
We see that the VarType can be used on a variable of type Object. Add another statement that casts the first variable to the Object type. VarType then resolves the Object variable's type to its most derived type (String).
New lines in program: VB.NET
Dim a As String = "cat"
' Cast to Object.
Dim value As Object = a
What happens inside the VarType function? The function basically calls the GetType function, which we also used in the above program. Then it converts the result of GetType to a String representation.Strings
The VarType function is based on the GetType function, but it presents a more Visual Basic oriented type system to you. It will return the best type for variables such as Integers, which can simplify your VB.NET programs.
Note: It is most useful when you must resolve the most derived type from an Object or other base type.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.