Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Syntax and Types

Variables and Data Types

Learn how to declare variables in Visual Basic .NET with Dim, Const and type inference, and how Integer, Long, Double, Decimal, Boolean, Char and String behave, including value versus reference types.

A variable is a named place in memory that holds a value of a particular type. VB.NET is statically typed: the compiler knows the type of every variable and checks your code against it. This catches many mistakes before the program runs. In this lesson you learn how to declare variables, choose the right numeric type, and understand how value types and reference types behave. Listings are VB.NET (read-only), and each topic has a runnable C# stand-in using the identical .NET types.

Declaring variables

Use Dim (short for "dimension") followed by a name, As, and a type:

VB
Dim count As Integer
Dim price As Double = 19.99
Dim title As String = "VB.NET"
Dim isReady As Boolean = True
Dim a, b As Integer          ' both are Integer
Dim x As Integer = 1, y As Double = 2.5

A variable without an initial value gets the default value of its type: 0 for numbers, False for Boolean, Nothing for strings and other references.

With local type inference (Option Infer On, the default) the compiler works out the type from the initial value:

VB
Dim n = 42            ' Integer
Dim pi = 3.14159      ' Double
Dim name = "Ada"      ' String
Dim big = 3000000000  ' Long (does not fit in Integer)

Inference only applies to local variables that have an initial value. The type is still fixed at compile time: n = "hello" afterwards is an error.

Constants

A Const is a named value that never changes. It must be initialized with a compile-time constant.

VB
Const TaxRate As Double = 0.2
Const AppName As String = "Shop"

By convention use PascalCase names. Local variables are camelCase (totalPrice). Names may contain letters, digits and underscores, cannot start with a digit and cannot be reserved words (put a keyword in brackets, [End], if you really must).

The built-in types

Each VB keyword is an alias for a .NET type:

VB type .NET type Size Range / use
Byte System.Byte 1 byte 0 to 255
Short Int16 2 -32,768 to 32,767
Integer Int32 4 about -2.1 to 2.1 billion
Long Int64 8 about ยฑ9.2 x 10^18
Single Single 4 floating point, ~7 digits
Double Double 8 floating point, ~15 digits
Decimal Decimal 16 base-10, 28 digits; use for money
Boolean Boolean 1 True or False
Char Char 2 a single UTF-16 character
String String varies text (reference type)
Date DateTime 8 date and time
Object Object varies anything

Integer-like unsigned variants exist too: SByte, UShort, UInteger, ULong.

Choosing between Double and Decimal

Double stores binary fractions, so many decimal numbers are only approximated. 0.1 + 0.2 is not exactly 0.3. For money or anything where decimal digits must be exact, use Decimal. Literals have type suffixes: 5D or 5@ for Decimal, 5.5R for Double, 5L for Long, 5S for Short. A fractional literal such as 19.99D is a Decimal.

C# Stand-in (C#): why Decimal exists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In C#, 0.1m is the Decimal literal; in VB.NET you write 0.1D. The first comparison prints False for the Double result and True for the Decimal one.

Integer division and overflow

VB has two division operators: / always returns a Double (or Decimal for decimals), while \ performs integer division. Mod returns the remainder.

VB
Console.WriteLine(7 / 2)    ' 3.5
Console.WriteLine(7 \ 2)    ' 3
Console.WriteLine(7 Mod 2)  ' 1

By default VB checks arithmetic overflow in integer types and throws an OverflowException (Integer.MaxValue + 1 fails at runtime). C# is unchecked by default, so this behaviour differs.

C# Stand-in (C#): integer division, remainder and checked overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Value types and reference types

.NET has two kinds of types:

  • Value types (numbers, Boolean, Char, Date, Structure, Enum) hold their data directly. Assigning copies the value.
  • Reference types (String, arrays, classes, Object, delegates) hold a reference to an object on the heap. Assigning copies the reference, so both variables point at the same object.
VB
Dim a As Integer = 5
Dim b As Integer = a
b = 99
Console.WriteLine(a)        ' 5, unaffected

Dim list1 As New List(Of Integer) From {1, 2}
Dim list2 = list1           ' same object
list2.Add(3)
Console.WriteLine(list1.Count)   ' 3

Nothing means "no object" for a reference variable. Calling a method on Nothing throws a NullReferenceException.

C# Stand-in (C#): copy versus shared reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Scope and lifetime

A variable lives inside the block where it is declared. VB has block scope inside If, For and While, procedure scope for locals in Sub and Function, and module or class scope for fields declared outside procedures. Keep scope as narrow as possible.

VB
Module Program
    Private total As Integer      ' module-level: lives as long as the program

    Sub Main()
        For i As Integer = 1 To 3
            Dim square = i * i      ' exists only in this loop iteration
            total += square
        Next
        Console.WriteLine(total)    ' 14
        ' Console.WriteLine(square) would not compile
    End Sub
End Module

Static locals are a VB-specific feature: a Static counter As Integer inside a procedure keeps its value between calls.

Common mistakes

  • Using Double for money: use Decimal.
  • Declaring Dim a, b As Integer and assuming only b is Integer. In VB.NET both are.
  • Dividing integers with / and expecting an integer result.
  • Forgetting that Nothing strings crash .Length: test first or use String.IsNullOrEmpty.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type does the compiler infer for Dim n = 42 with Option Infer On?

    An integer literal that fits in 32 bits infers Integer.
  2. 2. Which type should you normally use to store prices?

    Decimal is base-10 and avoids binary rounding errors such as 0.1 + 0.2.
  3. 3. What does 7 \ 2 evaluate to in VB.NET?

    The backslash operator is integer division and discards the fractional part.
  4. 4. After Dim b = a, where a is a List, what happens when you add to b?

    List is a reference type; the assignment copies the reference, not the object.
  5. 5. In Dim a, b As Integer, what is the type of a?

    Unlike VB6, VB.NET gives every variable in the list the declared type.

Summary

  • Declare with Dim name As Type; Option Infer On lets the compiler infer local types; Const defines fixed values.
  • Core types: Integer, Long, Double, Decimal (money), Boolean, Char, String, Date, Object.
  • / gives fractional results, \ is integer division, Mod is remainder; integer overflow throws.
  • Value types copy on assignment; reference types share one object; Nothing is the null reference.
  • Keep variables in the narrowest scope that works.

Next: Operators and Expressions