VarType. This built-in Function determines the type of a variable in VB.NET. This variable could be of type Object or a more derived type. It returns a VariantType.
With the VarType function and the VariantType enumeration, we test the type of variables such as Integer types. We often use VarType and VariantType with If-Statements.
Example. First, this program calls VarType on an Integer. 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.
Module Module1
Sub Main()
' Integer.
Dim value As Integer = 5
' Get VarType.
Dim type As VariantType = VarType(value)
' Write string representation.
Console.WriteLine(type.ToString())
' Show GetType method.
Console.WriteLine(value.GetType().ToString())
' You can check the VariantType against constants.
If type = VariantType.Integer Then
Console.WriteLine("It's an integer!")
End If
End Sub
End ModuleInteger
System.Int32
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.
Info VarType can be used on a variable of type Object. It resolves the Object variable's type to its most derived type (String).
Dim value As String = "cat"String
System.String
A discussion. What happens inside the VarType function? It calls the GetType function. Then it converts the result of GetType to a String representation.
Tip VarType is most useful when you must resolve the most derived type from an Object or other base type.
A summary. The VarType function is based on the GetType function. It will return the best type for variables such as Integers, which can simplify your VB.NET programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 19, 2023 (edit).