Variables and Constants
Prerequisites: Your first program
A variable is a named place to store a value. Declare one with
Dim:
Module Program
Sub Main()
Dim city As String = "Lagos"
Dim temperature As Integer = 24
Console.WriteLine("It is " & temperature & " degrees in " & city)
temperature = 27
temperature += 1
Console.WriteLine(temperature)
Dim count = 10 ' type inferred: Integer
Dim price = 4.5 ' type inferred: Double
Console.WriteLine(count.GetType().Name & " " & price.GetType().Name)
End Sub
End Module
It is 24 degrees in Lagos
28
Int32 Double
Dim name As Type = valuedeclares a variable with a type and an initial value.=assigns a new value;+=,-=,*=,/=, and&=update it.- With
Option Infer On(the default),Dim count = 10infers the type from the value. The type is still fixed:countis anIntegerforever. - A single quote
'starts a comment.
Default values
A variable declared without a value gets its type's default:
Module Program
Sub Main()
Dim n As Integer
Dim flag As Boolean
Dim name As String
Console.WriteLine(n)
Console.WriteLine(flag)
Console.WriteLine(name Is Nothing)
End Sub
End Module
main.vb(8) : warning BC42104: Variable 'name' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(name Is Nothing)
~~~~
0
False
True
Numbers start at 0 and Booleans at False. A String starts as
Nothing — "no object at all" — and the compiler warns that using
it might fail. Give variables a value when you declare them.
Several at once
Module Program
Sub Main()
Dim x, y As Integer
Dim first As String = "Ada", last As String = "Lovelace"
x = 3
y = 4
Console.WriteLine($"{x} {y} {first} {last}")
End Sub
End Module
3 4 Ada Lovelace
Constants
A Const can't change after it's declared — use it for fixed values:
Module Program
Const TaxRate As Decimal = 0.2D
Const AppName As String = "Invoice Maker"
Sub Main()
Dim net As Decimal = 150D
Console.WriteLine($"{AppName}: tax on {net} is {net * TaxRate}")
End Sub
End Module
Invoice Maker: tax on 150 is 30.0
The D suffix makes 0.2D a Decimal literal.
Naming
camelCasefor local variables and parameters (totalPrice),PascalCasefor everything else (procedures, properties, constants, classes).- Names can't start with a digit or be a keyword — unless you wrap them
in brackets:
Dim [Next] As Integer. - Because VB is case-insensitive,
totalandTotalare the same name.
Practice
Declare a constant HoursPerDay of 24 and a variable days of 7,
compute hours, and print "7 days = 168 hours".
Show solution
Module Program
Const HoursPerDay As Integer = 24
Sub Main()
Dim days = 7
Dim hours = days * HoursPerDay
Console.WriteLine($"{days} days = {hours} hours")
End Sub
End Module
7 days = 168 hours