Visual Basic.NET 2008 > Using Variables and Data Types

<< Previous Page Next Page >>

vb variable - Variables in Visual Basic 2008

In Visual Basic, as in any other programming language, variables store values during a program's execution. A variable has a name and a value. The variable UserName, for example, can have the value Joe, and the variable Discount can have the value 0.35. UserName and Discount are variable names, and Joe and 0.35 are their values. Joe is a string (that is, text or an alphanumeric value), and 0.35 is a numeric value. When a variable's value is a string, it must be enclosed in double quotes. In your code, you can refer to the value of a variable by the variable's name.

In addition to a name and a value, variables have a data type, which determines what kind of values we can store to a variable. VB 2008 supports several data types (and they're discussed in detail later in this chapter). It's actually the Common Language Runtime (CLR) that supports the data types, and they're common to all languages, not just to Visual Basic. The data type of a variable is specified when the variable is declared, and you should always declare variables before using them. To declare a variable, enter the Dim statement, followed by the variable's name, the As keyword, and the variable's type:

Dim Amount As Decimal

Decimal is a numeric data type; it can store both integer and noninteger values. For example, the following statements calculate and display the discount for the amount of $24,500:

Dim Amount As Decimal
Dim Discount As Decimal
Dim DiscountedAmount As Decimal
Amount = 24500
Discount = 0.35
DiscountedAmount = Amount * (1 - Discount)
MsgBox(”Your price is $” & DiscountedAmount.ToString)

If you enter these statements in a button's Click event handler to test them, the compiler may underline the statement that assigns the value 0.35 to the Discount variable and generate an error message. To view the error message, hover the pointer over the underlined segment of the statement in error. This will happen if the Strict option is on. (I discuss the Strict option, along with two more options of the compiler, later in this chapter.) By default, the Strict option is off and the statement should generate an error.

The compiler treats any numeric value with a fractional part as a Double value and detects that you're attempting to assign a Double value to a Decimal variable. To convert the numeric value to the Decimal type, use the following notation:

Discount = 0.35D

As you will see later, the D character at the end of a numeric value indicates that the value should be treated as a Decimal value, and there are a few more type characters (see Table 2.2 later in this chapter). I've used the Decimal data type here because it's commonly used in financial calculations. The message that this expression displays depends on the values of the Discount and Amount variables. If you decide to offer a better discount, all you have to do is change the value of the Discount variable. If you didn't use the Discount variable, you'd have to make many changes throughout your code. In otherwords, if you coded the line that calculated the discounted amount as follows, you'd have to look for every line in your code that calculates discounts and change the discount from 0.35 to another value:

DiscountedAmount = 24500 * (1 - 0.35)

By changing the value of the Discount variable in a single place in your code, the entire program is up-to-date.

Declaring Variables in Visual Basic 2008

In most programming languages, variables must be declared in advance. Historically, the reason for doing this has been to help the compiler generate the most efficient code. If the compiler knows all the variables and their types ahead of time, it can produce the most compact and efficient, or optimized, code. For example, when you tell the compiler that the variable Discount will hold a number, the compiler sets aside a certain number of bytes for the Discount variable to use.

One of the most popular, yet intensely criticized, features of BASIC was that it didn't force the programmer to declare all variables. As you will see, there are more compelling reasons than speed and efficiency for declaring variables. For example, when a compiler knows the types of variables in advance, it can catch many errors at design or compile time — errors that otherwise would surface at runtime. When you declare a variable as Date, the compiler won't let you assign an integer value to it.

When programming in Visual Basic 2008, you should declare your variables because this is the default mode, and Microsoft recommends this practice strongly. If you try to use an undeclared variable in your code, VB 2008 will throw an exception. It will actually catch the error as soon as you complete the line that uses the undeclared variable, underlining it with a wiggly line. It is possible to change the default behavior and use undeclared variables the way most people did with earlier versions of VB (you'll see how this is done in the section ‘‘The Strict, Explicit, and Infer Options,'' later in this chapter), but all the examples in this tutorial use explicitly declared variables.

In any case, you're strongly encouraged to declare your variables. To declare a variable, use the Dim statement followed by the variable's name, the As keyword, and its type, as follows:

Dim meters As Integer
Dim greetings As String

The first variable, meters, will store integers, such as 3 or 1,002; the second variable, greetings, will store text. You can declare multiple variables of the same or different type in the same line, as follows:

Dim Qty As Integer, Amount As Decimal, CardNum As String

If you want to declare multiple variables of the same type, you need not repeat the type. Just separate all the variables of the same type with commas and set the type of the last variable:

Dim Length, Width, Height As Integer, Volume, Area As Double

This statement declares three Integer variables and two Double variables. Double variables hold fractional values (or floating-point values, as they're usually called) that are similar to the Single data type, except that they can represent noninteger values with greater accuracy.

You can use other keywords in declaring variables, such as Private, Public, and Static. These keywords are called access modifiers because they determine which sections of your code can access the specific variables and which sections can't. You'll learn about these keywords in later sections of this chapter. In the meantime, bear in mind that all variables declared with the Dim statement exist in the module in which they were declared. If the variable Count is declared in a subroutine (an event handler, for example), it exists only in that subroutine. You can't access it from outside the subroutine. Actually, you can have a Count variable in multiple procedures. Each variable is stored locally, and they don't interfere with one another.

Variable-Naming Conventions

When declaring variables, you should be aware of a few naming conventions. A variable's name

  • Must begin with a letter, followed by more letters or digits.

  • Can't contain embedded periods or other special punctuation symbols. The only special character that can appear in a variable's name is the underscore character.

  • Mustn't exceed 255 characters.

  • Must be unique within its scope. This means that you can't have two identically named variables in the same subroutine, but you can have a variable named counter in many different subroutines.

Variable names in VB 2008 are case-insensitive: myAge, myage, and MYAGE all refer to the same variable in your code. Actually, as you enter variable names, the editor converts their casing so that they match their declaration.

Variable Initialization

VB 2008 allows you to initialize variables in the same line that declares them. The following statement declares an Integer variable and initializes it to 3,045:

Dim distance As Integer = 3045

This statement is equivalent to the following two:

Dim distance As Integer
distance = 3045

It is also possible to declare and initialize multiple variables, of the same or different type, on the same line:

Dim quantity As Integer = 1, discount As Single = 0.25

Type Inference

As Imentioned earlier, one of the trademark features of BASIC, including earlier versions of Visual Basic, was the ability to use variables without declaring them. It has never been a recommended practice, yet VB developers loved it. This feature is coming back to the language, only in a safer manner. VB 2008 allows you to declare variables by assigning values to them. The compiler will infer the type of the variable from its value and will create a variable of the specific type behind the scenes. The following statement creates an Integer variable:

Dim count = 2999

To request the variable's type, use the GetType method. This method returns a Type object, which represents the variable's type. The name of the type is given by the ToString property. The following statement will print the highlighted string in the Immediate window:


The count variable is of the Integer type. If you attempt to assign a value of a different type to this variable later in your code, such as a date, the editor will underline the value and generate the warning Value of type ‘Date' cannot be converted to Integer. The compiler has inferred the type of the value assigned initially to the variable and created a variable of the same type. That's why subsequent statements can't change the variable's type. You can turn off type inference by inserting the following statement at the top of the module:

Option Infer Off

Alternatively, you can turn on or off this option in the project's Properties pages. If the Infer option is off, the compiler will handle variables declared without a specific type depending on the Strict option. If the Strict option is off, the compiler will create an Object variable, which can store any value, even values of different types in the course of the application. If the Strict option is on, the compiler will reject the declaration; it will underline the variable's name with a wiggly line and generate the following warning: Option Strict On requires all variable declarations to have an As clause.

For more information on the various variable declaration–related options of the compiler, see the section "The Strict, Explicit, and Infer Options," later in this chapter. In the next sections, you'll explore the various data types of Visual Basic, and I will use explicit declarations, which is the recommended best practice for creating and using variables in your code.

<< Previous Page Next Page >>

Table of Contents

  1. VB.NET Variables
  2. Declaring Variables in VB 2008
  3. Types of Variables in VB.NET 2008
    1. Numeric Variables
    2. Integer Variables
    3. Infinity and Other Oddities
    4. Byte Variables
    5. Boolean Variables
    6. String Variables
    7. Character Variables
    8. Date Variables
    9. Data Type Identifiers
  4. The Strict, Explicit, and Infer Options
  5. Object Variables
  6. Variables as Objects
  7. Converting Variable Types
  8. Formatting Numbers
  9. User-Defined Data Types
  10. Examining Variable Types
  11. IsNumeric(), IsDate() and IsArray()
  12. Why Declare Variables?
  13. A Variable's Scope
  14. A Variable's Lifetime
  15. Constants in Visual basic 2008
  16. Arrays in Visual Basic 2008
  17. Initializing Arrays and Array Limits
  18. Multidimensional Arrays
  19. Dynamic Arrays Copyright 2011 All Rights Reserved
  Home | Useful links | Contact us | Privacy Policy