Thursday, February 17, 2011

Catch about Dynamic Arrays

I found a catch with arrays, dynamic arrays and scalar variables that we use in VB Script while working with QTP.

Lets start with dynamic arrays:
We declare dynamic array somewhat this way:

Dim myArray()

Before using a dynamic array, the QTP help clearly states under "array variables" that "To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension"

So before assigning values to elements in the dynamic array ReDim it this way:
ReDim myArray(10)

After this, you can assign values to the elements of this array by accessing through subscript.

The Catch:
You cannot assign an array to a dynamic array directly by a simple equal statement. This often happens when you try to assign an array returned by a function to an array declared as a dynamic array.


Example 1:
Dim myArray()

ReDim myArray(10)

myArray = fun_functionThatReturnsAnArray(var1, var2)
'assuming that the function returns an array of size 10

This will result in a "Type Mismatch" error. The reason being that the dynamic array declared will have its every element of type "User Defined Type".

Solution: do not declare the array as a dynamic array. Declare it simply as Dim myArray and assign the return value of function to this in this way: 
myArray = fun_functionThatReturnsAnArray(var1, var2)


Example 2:
In the example 1, if you assign the array in the following way:

myArray() = fun_functionThatReturnsAnArray(var1, var2)

this will result in a "Subscript out of range: 'myArray'" error.

Solution: Do not use braces in the assignment statement.

No comments: