Dim Statement

   
Dim Statement

Syntax

 [   accessmodifier   ] [Shared] [Shadows] [readonly] Dim [WithEvents] _   varname   [([   subscripts   ])] _              [As [New]   type   ] [= initexpr] 
accessmodifier (optional; Keyword)

Can be one of Public , Protected , Friend , Protected Friend , Private , or Static . If one of these is included, the Dim keyword can be omitted.

Shared (optional; Keyword)

Indicates the the variable is not associated with any particular class instance but is accessible directly using the class name and is therefore "shared" by all class instances.

Shadows (optional; Keyword)

Indicates that the variable shadows any programming elements ( variables , procedures, enums, constants, etc.) of the same name in a base class.

WithEvents (optional; Keyword)

In an object variable definition, indicates that the object will receive event notification

varname (required)

The name of the variable

subscripts (optional)

Dimensions of an array variable

New (optional; Keyword)

Keyword that creates an instance of an object

type (optional unless Option Strict is On )

The data type of varname

initexpr (optional)

Any expression that provides the initial value to assign to the variable; cannot be used if an As New clause is used

Description

Declares and allocates storage space in memory for variables. The Dim statement is used either at the start of a procedure or the start of a module to declare a variable of a particular data type.

Rules at a Glance

  • Public , Friend , Shared , Shadows , and ReadOnly can only be used at the module, namespace, or file level, not at the procedure level.

  • Protected and Protected Friend can appear only at the class level.

  • Private can appear only at the module level.

  • Static can be used only at the procedure level.

  • Static and Shared cannot appear in the same Dim statement.

  • Static cannot appear with either Shared or Shadows .

  • If you use WithEvents , the variable type cannot be of type Object.

  • Object is the default data type created when no data type is explicitly declared.

  • The declaration of a nonobject variable actually creates the variable. For an object variable, the variable is not created unless the optional New statement is used. If not, then the object variable is set to Nothing and must be assigned a reference to an existing object at some later point in the code.

  • When multiple variables are declared on the same line, if a variable is not declared with an explicit type declaration, then its type is that of the next variable with an explicit type declaration. Thus, in the line:

     Dim x As Long,   i   ,   j   ,   k   As Integer,   s   As String 

    the variables i , j , and k have type Integer. (In VB 6, the variables i and j have type Variant.)

  • VB.NET permits the initialization of variables in the same line as their declaration (at long last!). Thus, we may write:

     Dim   x   As Integer = 5 

    to declare an Integer variable and initialize it to 5. Similarly, we can declare and initialize more than one variable on a single line:

     Dim   x   As Integer = 6,   y   As Integer = 9 
  • Variables that are not explicitly initialized by the Dim statement have the following default values:

Data type

Initial value

All numeric types

Boolean

False

Date

01/01/0001 12:00:00 AM

Decimal

Object

Nothing

String

Nothing

  • Local variables can have procedure-level scope or block-level scope . A variable that is declared using the Dim keyword within a Visual Basic procedure but not within a code block has procedure-level scope; that is, its scope consists of the procedure in which it is declared. On the other hand, if a variable is declared inside a code block (i.e., a set of statements that is terminated by an End... , a Loop , or a Next statement), then the variable has block-level scope; that is, it is visible only within that block.

  • A variable cannot be declared using the Dim statement with WithEvents within a method, function, or procedure, since this creates a local variable with procedure-level scope only.

  • In VB.NET, all arrays have a lower bound of 0. This is a change from earlier versions of VB, where we could choose the lower bound of an array.

  • To declare a one-dimensional array variable, use one of the following example syntaxes:

     'Implicit constructor: No initial size & no initialization Dim Arrayname(  ) As Integer 'Explicit constructor: No initial size & no initialization Dim Arrayname() As Integer = New Integer(  ) {} 'Implicit constructor: Initial size but no initialization Dim Arrayname(6) As Integer 'Explicit constructor: Initial size but no initialization Dim Arrayname(  ) As Integer = New Integer(6) {} 'Implicit constructor: Initial size implied by initialization Dim Arrayname(  ) As Integer = {1, 2, 3, 4, 5, 6, 7} 'Explicit constructor, Initial size and initialization Dim Arrayname(  ) As Integer = New Integer(6) {1, 2, 3, 4, 5, 6, 7} 
  • To declare a multidimensional array, use one of the following example syntaxes:

     ' Two-dimensional array of unknown size Dim arrayname(,) As Integer ' Two-dimensional array of unknown size Dim arrayname(,) As Integer = New Integer(,) {} ' Two-dimensional array of size 3 by 2 Dim arrayname(3, 2) As Integer ' Two-dimensional array of size 3 by 2 Dim arrayname(,) As Integer = New Integer(3, 2) {} ' Two-dimensional array of size 3 by 2, initialized Dim arrayname(,) As Integer = {{1, 4}, {2, 5}, {3, 6}} ' Two-dimensional array of size 3 by 2, initialized Dim arrayname(,) As Integer = New Integer(3, 2) {{1, 4}, _                                          {2, 5}, {3, 6}} 
  • The WithEvents keyword cannot be used when declaring an array.

  • You can set or change the number of elements of an array using the ReDim statement.

  • The maximum allowed dimensions for an array are 60.

Programming Tips and Gotchas

  • When you declare an object reference as WithEvents , that object's events can be handled within your application. Object variables must be declared WithEvents at the module level to allow you to provide an error handler.

    When you declare an object variable as WithEvents in the declarations section of the module, the name of the object variable appears in the Object drop-down list at the top left of your code window. Select this and note that the events exposed by the object are available in the Procedure drop-down list at the top right of the code window. You can then add code to these event procedures in the normal way, as shown here:

     Private WithEvents oEmp As Employee Private Sub oEmp_CanDataChange(EmployeeCode As String, _                                Cancel As Boolean)     'event handling code goes here End Sub Private Sub oEmp_DataChanged(EmployeeCode As String)     'event handling code goes here End Sub 

    For a fuller description and discussion of the uses of WithEvents , Event , and RaiseEvent , see the Event, RaiseEvent, and WithEvents entries.

  • One word of warning when using the WithEvents keyword: if you are building a client-server system using a WithEvents object reference, you must ensure that the client machine gives permission for the server machine to create processes on it. Otherwise, even though the client can create instances of the object on the server, the server will not be able to call back to the client with event notifications. In fact, your application will not even launch before a "Permission Denied" or similar error is generated. You can alter the permissions on the client using the DCOM Config utility.

  • The way in which you declare an Object variable with the Dim statement dictates whether your application uses early binding or late binding. Early binding allows object references to be resolved at compile time. Late binding resolves an object reference at runtime, which has a negative impact on runtime efficiency. To optimize the performance, you should use early binding whenever possible. For more information on this, see the discussion of binding in Chapter 3.

  • When you declare an array without dimensioning it, you risk an ArgumentNullException exception if you attempt to iterate the array, as in the following code fragment:

     Dim aInts(  ), iCtr As Integer  For iCtr = 0 To UBound(aInts)    Console.WriteLine(aInts(iCtr))   ' Raises exception Next One workaround is to declare an empty array as having -1 element, as  the following code fragment illustrates: Dim aInts(-1) As Integer For iCtr = 0 to UBound(aInts)   ' For loop never executed    Console.WriteLine(aInts(iCtr)) Next 

VB.NET/VB 6 Differences

  • In VB 6, all variables declared using Dim without specifying a specific data type are created as Variants. In VB.NET, all variables whose data type is not specified are Objects.

  • When multiple variables are declared on a single line of code in VB 6, variables not explicitly assigned a data type are cast as variants. For example, in the statement:

     Dim   Var1   ,   Var2   ,   Var3   As String 

    both Var1 and Var2 are variants rather than strings. In VB.NET, the type declaration applies to all undeclared variables since the last explicit type declaration. So the previous statement in VB.NET would cast Var1 , Var2 , and Var3 as strings.

  • In VB 6, variables cannot be initialized at the same time they are declared. In VB . NET, variables can be assigned an initial value when they are declared.

  • In VB 6, all variables defined within a procedure using the Dim keyword have procedure-level scope. In VB.NET, variables defined using Dim in code blocks (such as loops ) have block-level scope and are not accessible throughout the procedure. Hence, code such as the following works under VB6 but may fail to compile under VB.NET:

     Dim iCtr As Integer 'Nested loop For iCtr = 0 To 10000    Dim iCtr2 As Integer    For iCtr2 = 0 To 10000    Next Next ' Reinitialize iCtr2 iCtr2 = 0 End Sub 
  • VB 6 supports fixed-length strings, but they are not supported in VB.NET.

  • In VB 6, if an object is instantiated using the New keyword as part of a Dim statement, testing for the validity of the object reference with a statement such as:

     If obj Is Nothing Then 

    always fails, since the statement itself reinstantiates the object if it is Nothing . In VB.NET, this undesirable behavior has been changed, and setting the object to Nothing destroyes the object.

  • In VB 6, you could instantiate an object instantiated using the New keyword as part of a Dim statement, release the object reference by setting it to nothing, then reinstantiate the object by referencing it or its members . In VB.NET, setting the object reference to Nothing destroys the object; subsequent attempts to reference the object generate a NullReferenceException exception.

  • In VB 6, arrays could be either fixed length or dynamic; in VB.NET, all arrays are dynamic.

  • VB 6 allows you to define the lower bound of an array when it is initialized. In VB.NET, all arrays have a lower bound of 0. For example, the VB 6 syntax:

     Dim array(1 To 20) As String 

    is not supported in VB.NET.

  • In VB.NET, an array cannot be declared using the New keyword. Practically, this means that you cannot create an array of creatable objects, and must instead use a collection. VB 6, in contrast, allows arrays of objects.

See Also

Private Statement, Public Statement, ReDim Statement, Static Statement, WithEvents Keyword

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net