Variables in Visual Basic .NET
Our first program will demonstrate how to declare and use variables in Visual Basic .NET. Here’s the full source code:
Imports System
Module Variables
Sub Main()
' Dim declares one or more variables
Dim a As String = "initial"
Console.WriteLine(a)
' You can declare multiple variables at once
Dim b As Integer = 1, c As Integer = 2
Console.WriteLine($"{b} {c}")
' Visual Basic .NET will infer the type of initialized variables
Dim d = True
Console.WriteLine(d)
' Variables declared without a corresponding
' initialization are default-valued. For example, the
' default value for an Integer is 0.
Dim e As Integer
Console.WriteLine(e)
' In Visual Basic .NET, you can use the shorthand assignment operator
' to declare and initialize a variable in one line
Dim f = "apple"
Console.WriteLine(f)
End Sub
End Module
In Visual Basic .NET, variables are explicitly declared and used by the compiler to check type-correctness of function calls, among other things.
Dim
declares one or more variables. You can declare multiple variables at once.
Visual Basic .NET will infer the type of initialized variables when you use the Dim
keyword without specifying a type.
Variables declared without a corresponding initialization are default-valued. For example, the default value for an Integer
is 0
.
In Visual Basic .NET, you can use the shorthand assignment operator to declare and initialize a variable in one line, similar to the :=
syntax in some other languages.
To run the program, save it as Variables.vb
and use the Visual Basic .NET compiler:
$ vbc Variables.vb
$ Variables.exe
initial
1 2
True
0
apple
This example demonstrates basic variable declaration and usage in Visual Basic .NET, including type inference, multiple variable declaration, and default values.