JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Declaring Variables

You need to store some data in your program—so you need to declare some variables. How does that work? Unlike VB6 and earlier versions of Visual Basic, you must declare all variables before using them by default in VB .NET, and you can do that with the Dim statement (which originally stood for dimension, as when you set the dimensions of an array); this statement is used at module, class, structure, procedure, or block level:

[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |
Private | Static }] [ Shared ] [ Shadows ] [ ReadOnly ] Dim [ WithEvents ]
name[ (boundlist) ] [ As [ New ] type ] [ = initexpr ]

Here are the parts of this statement:

  • attrlist—A list of attributes that apply to the variables you're declaring in this statement. You separate multiple attributes with commas.

  • Public—Gives variables public access, which means there are no restrictions on their accessibility. You can use Public only at module, namespace, or file level (which means you can't use it inside a procedure). Note that if you specify Public, you can omit the Dim keyword if you want to.

  • Protected—Gives variables protected access, which means they are accessible only from within their own class or from a class derived from that class. You can use Protected only at class level (which means you can't use it inside a procedure), because you use it to declare members of a class. Note that if you specify Protected, you can omit the Dim keyword if you want to.

  • Friend—Gives variables friend access, which means they are accessible from within the program that contains their declaration, as well as from anywhere else in the same assembly. You can use Friend only at module, namespace, or file level (which means you can't use it inside a procedure). Note that if you specify Friend, you can omit the Dim keyword if you want to.

  • Protected Friend—Gives variables both protected and friend access, which means they can be used by code in the same assembly, as well as by code in derived classes.

  • Private—Gives variables private access, which means they are accessible only from within their declaration context (usually a class), including any nested procedures. You can use Private only at module, namespace, or file level (which means you can't use it inside a procedure). Note that if you specify Private, you can omit the Dim keyword if you want to.

  • Static—Makes variables static, which means they'll retain their values, even after the procedure in which they're declared ends. You can declare static variables inside a procedure or a block within a procedure, but not at class or module level. Note that if you specify Static, you can omit the Dim keyword if you want to, but you cannot use either Shadows or Shared.

  • Shared—Declares a shared variable, which means it is not associated with a specific instance of a class or structure, but can be shared across many instances. You access a shared variable by referring to it either with its class or structure name, or with the variable name of an instance of the class or structure. You can use Shared only at module, namespace, or file level (but not at the procedure level). Note that if you specify Shared, you can omit the Dim keyword if you want to.

  • Shadows—Makes this variable a shadow of an identically named programming element in a base class. A shadowed element is unavailable in the derived class that shadows it. You can use Shadows only at module, namespace, or file level (but not inside a procedure). This means you can declare shadowing variables in a source file or inside a module, class, or structure, but not inside a procedure. Note that if you specify Shadows, you can omit the Dim keyword if you want to.

  • ReadOnly—Means this variable only can be read and not written. This can be useful for creating constant members of reference types, such as an object variable with preset data members. You can use ReadOnly only at module, namespace, or file level (but not inside procedures). Note that if you specify Shadows, you can omit the ReadOnly keyword if you want to.

  • WithEvents—Specifies that this variable is used to respond to events caused by the instance that was assigned to the variable. Note that you cannot specify both WithEvents and New in the same variable declaration.

  • name—The name of the variable. You separate multiple variables by commas. If you specify multiple variables, each variable is declared of the data type given in the first As clause encountered after its name part.

  • boundlist—Used to declare arrays; gives the upper bounds of the dimensions of an array variable. Multiple upper bounds are separated by commas. An array can have up to 60 dimensions.

  • New—Means you want to create a new object immediately. If you use New when declaring an object variable, a new instance of the object is created. Note that you cannot use both WithEvents and New in the same declaration.

  • type—The data type of the variable. Can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, or String; or the name of an enumeration, structure, class, or interface. To specify the type, you use a separate As clause for each variable, or you can declare a number of variables of the same type by using common As clauses. If you do not specify type, the variable takes the data type of initexpr. Note that if you don't specify either type or initexpr, the data type is set to Object.

  • initexpr—An initialization expression that is evaluated and the result is assigned to the variable when it is created. Note that if you declare more than one variable with the same As clause, you cannot supply initexpr for those variables.

Each attribute in the attrlist list must use this syntax:

<attrname [({ attrargs | attrinit })]>

Here are the parts of the attrlist list:

  • attrname—Name of the attribute.

  • attrargs—List of arguments for this attribute. Separate multiple arguments with commas.

  • attrinit—List of field or property initializers for this attribute. Separate multiple arguments with commas.

Here are a few examples where I'm declaring variables—note in particular that you can initialize the value in a variable when you declare it by using the = sign and assigning it a value, as here, where I'm initializing the first variable to the value 1, and the second one to "Bob Owens":

Dim EmployeeID As Integer = 1
Dim EmployeeName As String = "Bob Owens"
Dim EmployeeAddress As String

The default data type if you do not specify one is Object (not Variant, as in VB6, because Variant no longer exists). Note also that if you do not specify an initialization value for a variable, Visual Basic will initialize it to a default value for its data type:

  • 0 for all numeric types (including Byte).

  • Binary 0 for Char.

  • Nothing for all reference types (including Object, String, and all arrays). Nothing means there is no object associated with the reference.

  • False for Boolean.

  • 12:00 AM of January 1 of the year 1 for Date.

To create a new object, you use the New keyword, as in this case, where I'm creating a new VB .NET LinkLabel control (which we'll see in Chapter 5):

Dim LinkLabel1 As New LinkLabel

Note that you do not have to create a new object using New when you declare it—you can create it later using New, after it's been declared:

Dim LinkLabel1 As LinkLabel
        
LinkLabel1 = New LinkLabel()

In VB6, you could also declare an object with the New keyword to create that object—but although it seemed that that would create the new object immediately, the object wasn't actually created until used in code, resulting in some hard-to-find bugs. This has been fixed in VB .NET, where the new object is created immediately if you declare it with the New keyword.

Also in Visual Basic 6.0, you could declare variables of different types in the same statement, but you had to specify the data type of each variable or it defaulted to Variant (which no longer exists). Here's an example:

Dim count1, count2 As Integer   'count1 is a Variant, count2 is an Integer.

In Visual Basic .NET, on the other hand, you can declare multiple variables of the same data type without having to repeat the type keyword:

Dim count1, count2 As Integer   'count1 is an Integer, count2 is an
    Integer.

Some people think that variable names should be prefixed to indicate their data type. Table 2.3 lists the some of the prefixes that have become conventional for the Visual Basic data types (for more on these types, see the next topic). This use is optional.

Table 2.3: Variable prefixes.

Data type

Prefix

Boolean

bln

Byte

byt

Collection object

col

Date (Time)

dtm

Double

dbl

Error

err

Integer

int

Long

lng

Object

obj

Single

sng

String

str

User-defined type

udt

For example, here are some prefixed variable names:

blnTrueFalse        'Boolean
intCounter  'Integer
sngDividend 'Single

Using variable prefixes this way provides some clue as to the variable's type, and that can be extraordinarily helpful if someone else will be reading your code.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor