Variables in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes the variables in Visual Basic .NET

Generally speaking, the variables are among the most fundamental components of programming.

A variable is an object that stores a value which can be a number, letter, string, date etc.

If a variable contains a value, the program can manipulate it. Meaning, it can perform arithmetic operations on numbers, string operations on strings (concatenate, calculate substrings, finding a match within string and so on), date operations (find the difference between two dates, add a time period to a date), and so forth.

The variable's behavior is determined by:

1. Scope - it indicates the scope levels from where the variable can be accessed (private, public etc.)
2. Data type - can be an Integer, String, Boolean etc.
3. Accessibility - determines what code in other modules can access the variable
4. Lifetime - determines how long the variable value is valid

For instance, any variable declared inside a subroutine has scope equal to the subroutine and cannot be accessed by the code outside of the subroutine.

    Private Sub DoSomething()
        Dim InsideVariable As String = String.Empty;
        ' Do Something with the variable
    End Sub

    Console.Write(InsideVariable)
    ' ERROR: variable is not in scope (can't be accessed from outside)


In Visual Basic you use the keyword Dim to tell Visual Basic officially that you want to declare a variable.

You can avoid the Dim only if you specify Private, Public, Protected etc. however a variable delared using a Dim keyword is Private by default so the next two declarations are identical:

    Dim MyString As String = String.Empty
    Private MyString As String = String.Empty

Previous Lesson | Next Lesson


Share This