Tuesday, June 16, 2009

Dynamic and Static Array Declarations

There are 2 methods commonly used for declaring arrays. While both have their place and usage, most programmers prefer the dynamic array that is declared at run-time to provide the most flexibility. The static array is great if you have a set structure that will never change. For instance, an array that holds the days of the week, months in the year, or even the colors in a rainbow. These won't change and they won't be data driven so in this case, a static array will be best.

Static Arrays

Arrays can be declared in many ways. These first examples demonstrate arrays that are created at "design time" รข€“ (programmer sets the value(s) and length). This array is "hard coded". Hard coded means that the values and length of the array are established at the time the array is declared and isn't based on user input or stored data. It won't vary while the program is running. Notice that there is more than one way to declare this type of arrays.

string[] strFruitArray = {"apple", "banana", "orange", "grape", "pineapple"};
string[] strFruitArray = new string[]{"apple", "banana", "orange", "grape", "pineapple"};
strFruitArray = new string [5] {"apple", "banana", "orange", "grape", "pineapple"};

Regardless of which method is used to declare the array, referencing the individual values is done the same way

strFruitArray[0] = "apple"
strFruitArray[1] = "banana"
strFruitArray[2] = "orange"
strFruitArray[3] = "grape"
strFruitArray[4] = "pineapple"

Dynamic Arrays

Most of the time, we need to have arrays that we won't know the values or how many items. The next example is an example of a completely dynamic array. The only information set at design time is the data type (int), the variable name (intArray), and that it is an array ([]). The values and the number of values will be based on user input or data retrieved from at runtime. The following is an example of how this type of array is declared.

No length or values set at the time of declaration. Set this at the class level (see full example download) in order for it to be visible to the entire form class.
int[] intArray;

Fixed length at the time of declaration but not the values
intArray = new int[5];

Practical Example of a Dynamic Array

No comments: