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.
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.
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!
What happens if you change the "Dim
value As Integer" line to "Dim
value As String
"? The result of the program will be different.
If
-statement will not evaluate to True and the final line will not be printed to the output.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
What happens inside the VarType
function? It calls the GetType
function. Then it converts the result of GetType
to a String
representation.
VarType
is most useful when you must resolve the most derived type from an Object or other base type.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.