Total .NET Analyzer Rule Documentation  

RedimNewVariable Rule

Do not use the ReDim statement for undeclared array variables.

Remarks

The ReDim statement is used to reallocate storage space for array variables. The ReDim statement can be used to modify a variable that has already been declared.

When Option Explicit is off, however, Visual Basic .NET does not require you to declare a variable before using it. In this case, you are permitted to use the ReDim statement to declare a new variable.

For instance, the following code uses the ReDim statement for the array variable "myArray":


' VB
Sub MyArrayClass(ByVal arrayElements As Integer)
ReDim myArray(arrayElements)
End Sub


Although Visual Basic .NET allows this, it is a very unwise practice for several reasons, including:

1. If a variable is not declared, the Visual Basic compiler will guess at its type based on the data that is put into it. Often, this guess causes inefficient type use. Additionally, the Visual Basic compiler has to generate a great deal of handling code to cast variables from one data type to another. This can lead to poor performance, increased program size, and unexpected results.

2. Use of non-declared variables eliminates almost all the benefits of the .NET common type system, which enables cross-language integration, type safety, and high performance code execution.

3. Non-declared variables make code very difficult to understand and debug. For large, complex applications, non-declared variables can result in program code that is indecipherable.

4. Use of non-declared variables makes it easy to inadvertently declare a new variable by mistyping the name of an existing variable.

Resolution

The ReDim statement should only be used for array variables that have already been declared using the Dim statement. For instance, the code example above could be modified to:

' VB
Sub MyArrayClass(ByVal arrayElements As Integer)
Dim myArray(arrayElements)
End Sub


In general, you should turn Option Explicit On to disallow implicit variable declarations.

See Also

ReDim Statement

Total .NET Analyzer Option Explicit Rule