Pages

Sunday, March 6

Arrays in QTP - Part 2

In the 1st part of this post we discussed about Static(fixed size) arrays. Now we are going to discuss another type of array - Dynamic Array.

Dynamic Arrays:-

A dynamic array, also called resizable array is a variable-size array that allows elements to be added or removed at runtime. Dynamic arrays are useful when size of the array cannot be determined at the time of declaration.


Dynamic or Variable Sized Array
    2.1. Single dimentional Dynamic Array
    2.2. Multi-dimentional Dynamic Array


Dim myArray()  'create a dynamic array.



It creates an array, which can be resized at runtime. For initial use, it must be initialized with some value i.e. size

This will be done using ReDim.

ReDim myArray(3)   'before using first time

Now you can assign values to array

myArray(0)=43
myArray(1)=90
myArray(2)=34
myArray(3)=76

Dynamic array can be resized n number of times, but remember, if you resize it again using ReDim, all its previous data will lost.
For that purpose, Preserve is used with ReDim.

ReDim Preserve myArray(5)

myArray(4)=67
myArray(5)=82

ReDim Preserve resize the array by keeping existing data safe!!




Dynamic arrays can be Multidimensional but only one of the dimensions (the 'right side') can be changed. Refer the below code..


Dim myArray()
Redim myArray(1,0)
myArray(0,0) = "John"
myArray(1,0) = 21
msgbox (ubound (myArray, 2)) '0
Redim preserve myArray(ubound (myArray, 1), ubound (myArray, 2) + 1)
myArray(0,1) = "Bob"
myArray(1,1) = 21
msgbox (ubound (myArray, 2)) '1

So point to be noted about Dynamic Arrays:-

(i) -   Dynamic Arrays are variable-size arrays that allows elements to be added or removed at runtime

(ii) -  Dynamic Arrays are useful when size of the array cannot be determined at declaration time
  
(iii) - Dynamic Arrays must be initialized with some value i.e. size before using first time

(iv) - Dynamic Arrays can be resized n number of time

(v) - 'Preserve' must be used with ReDim to keep the existing data of Dynamic Arrays


In case of any queries, please post your comments. Have a nice QTPing :)