Variables, Data Types, and Constants (Visual Basic)
Overview
Visual Basic provides a rich set of keywords for declaring variables, specifying data types, and defining constants. Understanding these concepts is essential for building robust .NET applications.
Declaring Variables
Use the Dim
statement to declare a variable. The As
clause specifies its data type.
Dim counter As Integer
Dim message As String
Dim isValid As Boolean = True
Dim data() As Byte = New Byte(9) {0,1,2,3,4,5,6,7,8,9}
You can also declare multiple variables of the same type in one line:
Dim x, y, z As Double
Data Types
VB.NET includes both built‑in and .NET Framework types. The table below lists the most common types.
VB Type | .NET Type | Size | Range / Description |
---|---|---|---|
Boolean | System.Boolean | 1 byte | True or False |
Byte | System.Byte | 1 byte | 0 to 255 |
Char | System.Char | 2 bytes | Unicode character |
Decimal | System.Decimal | 16 bytes | 28‑28 significant digits |
Double | System.Double | 8 bytes | ±5.0 × 10⁻³² to ±1.7 × 10³⁸ |
Integer | System.Int32 | 4 bytes | ‑2,147,483,648 to 2,147,483,647 |
Long | System.Int64 | 8 bytes | ‑9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Object | System.Object | Reference | Base type of all .NET types |
String | System.String | Reference | Unicode text |
Single | System.Single | 4 bytes | ±1.5 × 10⁻⁴⁵ to ±3.4 × 10³⁸ |
UInteger | System.UInt32 | 4 bytes | 0 to 4,294,967,295 |
UShort | System.UInt16 | 2 bytes | 0 to 65,535 |
Structure | System.ValueType | Varies | User‑defined value type |
Option Strict
Enable Option Strict On
to enforce early binding and disallow implicit narrowing conversions. This helps catch type‑related errors at compile time.
Option Strict On
Dim i As Integer = 10
Dim d As Double = i ' OK – widening conversion
'Dim s As String = i ' Error: Option Strict On disallows implicit conversion
Constants
Use the Const
keyword for values that never change.
Const Pi As Double = 3.14159265358979
Const MaxItems As Integer = 100
Constants are implicitly Shared
and must be initialized at declaration.
Complete Example
The following example demonstrates variable declaration, type conversion, and constant usage.
Option Strict On
Module Module1
Const Greeting As String = "Hello, "
Sub Main()
Dim name As String = "World"
Dim times As Integer = 3
Dim result As String = Greeting & name
For i As Integer = 1 To times
Console.WriteLine(result)
Next
' Demonstrate conversion
Dim age As Byte = 30
Dim ageDouble As Double = CDbl(age) ' widening conversion
Console.WriteLine($"Age as Double: {ageDouble}")
Console.ReadLine()
End Sub
End Module