MSDN

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 TypeSizeRange / Description
BooleanSystem.Boolean1 byteTrue or False
ByteSystem.Byte1 byte0 to 255
CharSystem.Char2 bytesUnicode character
DecimalSystem.Decimal16 bytes28‑28 significant digits
DoubleSystem.Double8 bytes±5.0 × 10⁻³² to ±1.7 × 10³⁸
IntegerSystem.Int324 bytes‑2,147,483,648 to 2,147,483,647
LongSystem.Int648 bytes‑9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ObjectSystem.ObjectReferenceBase type of all .NET types
StringSystem.StringReferenceUnicode text
SingleSystem.Single4 bytes±1.5 × 10⁻⁴⁵ to ±3.4 × 10³⁸
UIntegerSystem.UInt324 bytes0 to 4,294,967,295
UShortSystem.UInt162 bytes0 to 65,535
StructureSystem.ValueTypeVariesUser‑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