O'Reilly logo

Learning Visual Basic .NET by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Variables

A variable is an object that can hold a value:

Dim myVariable As Integer = 15

In this example, myVariable is an object/variable of type Integer. You can assign values to that object, and then you can extract those values later. You initialize a variable by writing a definition and then assigning a value to that variable. The previous code line defines myVariable and initializes it with the value 15. The syntax for defining a variable is as follows:

            access-modifier 
            identifier As type [= value]

Access modifiers are discussed in Chapter 8; for now you'll use Dim.

Tip

The keyword Dim is short for dimension. This term dates back to the early days of Basic programming and is essentially vestigial.

An identifier is just an arbitrary name for a variable, method, class, or other element. In this case, the variable's identifier is myVariable. The keyword As signals that the term that follows is the type, in this case Integer.

Specifying Type with a Character

Rather than using a word to specify a variable's type, you can append a single character that corresponds to the type to the variable's name.

Tip

While type characters were preserved in the Visual Basic .NET language for continuity with VB6, many developers feel they should be avoided and that spelling out the type makes for clearer, easier-to-maintain code.

For example, rather than writing As Integer, you can use the suffix %, which has the same meaning. Thus, the following two lines are equivalent:

Dim myVariable As Integer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required