Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Declaring and Typing Arrays

The use of arrays is integral to almost any programming task. JScript has always had a method for creating arrays that can perform any task, but JScript arrays were never very efficient. The new arrays available through JScript .NET, which can exist side-by-side with JScript arrays, offer both performance and flexibility, but never both at the same time.

Declaring JScript and JScript .NET Arrays

The first step in working with arrays is to declare the array. Let's start by declaring a traditional JScript-style array:

var _JScriptArray:Array = new Array();
_JScriptArray[0] = "123";
_JScriptArray[2000] = 123;
_JScriptArray[500] = new Object();

The type of this array is Array, and the example creates a new instance of the Array class. Note that all the assignments in this example are valid, and that JScript-style arrays are not strongly typed. Everything that goes in the array is of type Object, and everything that comes out is of type Object. Therefore, you can assign a String object to array index 0, int to array index 2000, and new Object to array index 500.

JScript arrays are not bounded. New elements can be assigned on-the-fly. As you make assignments, a length function is updated so that the upper bounds of the array are always known. This comes in handy when you retrieve a JScript array and need to iterate over the contents. If some of the intermediate values were null, then you wouldn't be able to tell the end of the array without the length function. JScript arrays are extremely powerful, but there are some performance tradeoffs involved with them.

The following example demonstrates a variety of methods for finding the true 
end of a JScript array. The first method searches for null:var 
_JScriptArray:Array = new Array();
var _int:int = 0;

// Use JScript array like a stack
_JScriptArray[_int++] = "First Element";
_JScriptArray[_int++] = "Second Element";

// Now let's pass this off to a function that doesn't know its length

function DumpArray(_jsArray:Array) {
    var _i:int = 0;
    while(_jsArray[_i]) {

This isn't very great code. You need to have a handle on what the top of the array is at all times so that you can add elements on the end. Then you have to search for null. Furthermore, if you put an element at index 10, then the print function would miss it because this function stops at the first null. You could also do better with the length function, and you could take advantage of a couple other functions in the process. For example, the push function allows you to put values on the end of an array and increment the length pointer accordingly, and the pop function returns the very last element of the array, removes it from the end, and decrements the length pointer accordingly. You could rewrite the preceding example as follows:

var _JScriptArray:Array = new Array();

// Use JScript array like a stack
JScriptArray.push("First Element", "Second Element");
JScriptArray[9] = "Tenth Element";

// Now let's pass this off to a function that doesn't know its length

function DumpArray(_jsArray:Array) {
    for ( var _i = 0; i < _jsArray.length(); _i++ ) {

This code performs the same operations as the preceding example, but it isn't as error prone. After popping the 2 items on the stack, the 3rd through 9th elements are left unassigned, and the 10th value is assigned. The array dynamically sizes to 10 elements as soon as the 10th element is set. The DumpArray function won't stop after the second value and will proceed right through the null elements to element 10 and print the contents.

An important feature of JScript-style arrays is that they are sparse arrays, which means the elements don't have to be contiguous. In the first example you set elements 0, 500, and 2000. Memory isn't allocated for any other elements besides these three, but this introduces a few problems. For instance, the DumpArray function would try to iterate through 2,000 elements, just to print 3 of them. This isn't extremely efficient. CLR-style arrays provide better performance than this, and the next section covers them in detail.

Using CLR-Style Arrays

A CLR-style array has bounds and a definite length, so it can't be expanded and shrunk on-the-fly. This type of array is also strongly typed, meaning you get both compiler and runtime errors for performing incorrect assignments. Every element that comes out of a CLR-style array is of a specific type, so you don't have to check for types before casting. The following example creates a CLR-style array of String objects in JScript .NET. The type is a null array type, and the new keyword is used with a bounded array type to fully initialize the variable:

var _CLRArray:String[] = new String[10];

// We now have a CLR array of Strings with 10 elements
_CLRArray[0] = "Hello";
_CLRArray[9] = "World";
_CLRArray[10] = "Produces an error";  // IndexOutOfRangeException

This array is now strongly typed to String objects. If you attempt to assign any other type of variable (for example, an integer), either the object in question is cast to a String object or you get an InvalidCast error. All objects support the ToString() function, so you will almost never see an InvalidCast error when assigning objects or values to a String array. This can cause very unexpected results. To get an error by assigning an incorrect type, you need to change to another type of array. For example, you could use an array of Int32 objects, such as the following:

var _CLRArray:Int32[] = new Int32[10];

_CLRArray[0] = 1;
// This works because the string can be parsed as a number_CLRArray[1] = "123";  
_CLRArray[2] = "Hello"; // This fails

With this code, you get a compiler error on the third assignment. It's a basic type mismatch because the compiler knows "Hello" cannot be converted to or parsed as an Int32 object. A number of other array types will also fail when values can't be converted to or from the appropriate type.

You need to be aware that CLR arrays don't have any of the functions you have seen previously in the JScript arrays. You can't push and pop values onto and off arrays, they aren't sparse, and you can't expand them at will. They do have some other properties, though. By using the Length property, you can determine the number of elements in an array. You can use the CopyTo function to transfer array contents from one array to another. You can use the Rank property to determine the number of dimensions an array contains. Take a look at Listing 3.4, which demonstrates the use of the Length property and the CopyTo function.

Listing 3.4  Dynamically Sizing Fixed Arrays

import System;

var _WorkArray:Int32[] = new Int32[10];
var _WorkOffset:Int32 = 0;
var _CopyArray:Int32[];

while(_WorkOffset < 50) {
    while(_WorkOffset < _WorkArray.Length) {
        _WorkArray[_WorkOffset] = _WorkOffset;
    if ( _WorkArray.Length < 50 ) {
        _CopyArray = new Int32[_WorkArray.Length + 10];
        _WorkArray.CopyTo(_CopyArray, 0);
        _WorkArray = _CopyArray;
        Console.WriteLine("Expanded Array to " + _WorkArray.Length);

_WorkOffset = 0;
while(_WorkOffset < _WorkArray.Length) {

Listing 3.4 might seem to be quite a bit of code this early in the book. After all, you have not been introduced to while loops, conditional statements, and a number of other features that are used in this listing. So let's walk through the most important parts of Listing 3.4. First, it creates two arrays of type Int32. The work array is given bounds of 10. The copy array is not bounded and remains uninitialized until you fill up the work array. At this point, the copy array is declared to have bounds 10 greater than the work array, the contents of the work array is copied to the copy array, and the copy array is assigned to the work array so that work can continue.

You'll learn more about CLR-style arrays in the sections "Typing Arrays for Performance" and "Multidimensional Array Support" later in this chapter.

Typing Arrays for Performance

JScript-style arrays are slow because they aren't strongly typed. When you get an element in an array that isn't typed, you have no idea what kind of object you're getting. It could be a string, a hashtable, another array, or even a number. You just don't know, and neither does the computer. Therefore, you need code to do type checks and appropriate conversions before the value can be used.

CLR arrays are always typed. In order to create an instance of an array, the underlying type must be given first. Typed arrays can be created in two manners. Earlier in this chapter we talked about the language-specific manner of creating a typed array, which involves using a null array type to which you can later assign bounds by creating a new instance of a typed array. Another method is to create a variable of type System.Array. Later, you can assign it a typed array by using the System.Array.CreateInstance function. This method is extremely powerful because the type of array can be decided at runtime; however, this method also increases the chance of runtime exceptions because array assignments can't be typed and checked during compilation. The following example shows how to use both of these methods of creating typed arrays:

import System;

var _IntegerArray:Int32[] = new Int32[10];
var _StringArray:String[] = new String[10];
var _GenericArray:System.Array;

_GenericArray = _IntegerArray; //Success!
_GenericArray = _StringArray; //Success!

_GenericArray = System.Array.CreateInstance(


A generic CLR array has to be declared by using type System.Array. JScript interprets Array to mean a JScript array, even if the import System directive is present. This is for legacy purposes and prevents users from typing Microsoft.JScript.Array.

Note several neat things in the preceding example. First, you have two typed arrays that give maximum performance to the application. But you can also assign these arrays to the _GenericArray variable because it is of type System.Array, and all typed arrays inherit from this base class. (You'll learn more about inheritance in Chapters 6 and 7, "Interfaces and Class Members.") _GenericArray can be of any array type, but regardless of type, it has the performance of a typed array, without the compile-time warnings that would exist if you made a poor assignment to an array element. Notice that this example uses a special function on the System.Array class to create a String array. This looks pretty ugly, because it involves several levels of function calls, but it shows that arrays can be created with indeterminate types at runtime. In the example, you have to know the type of the Int32 and the String arrays, but you could have created any type of array by using the CreateInstance function. You can also create arrays that have a variable number of dimensions, as discussed in the following section.

Multidimensional Array Support

JScript .NET supports two types of multidimensional arrays. The first type is a standard equal-bounds array, in which all rows in the array are of the same length. The second type of array is a staggered array, which can have rows of different lengths. Staggered arrays can be effective when you're creating arrays in which some rows might have thousands of elements whereas other rows may contain very few or no elements.

Let's look first at the most common type of array, the equal-bounds array. In the type specifier for this array, you simply add one comma between the brackets for each additional dimension you need to introduce. In the new expression, you provide the bounds for each of the dimensions. This syntax makes creating a multidimensional array very easy. The following code demonstrates the creation of a 10-by-10 array, whose elements you initialize to create a multiplication table:

import System;

var myArray:Int32[,] = new Int32[10,10];
var i:int;
var j:int;

for(i = 0; i < 10; i++){
    for(j = 0; j < 10; j++){
        myArray[i,j] = (i+1)*(j+1);


An overloaded method of Array.CreateInstance allows for the creation of multidimensional arrays as well, and it is often useful when you're creating an array of a type that is not yet known or when the user can specify the number of dimensions (which might be the case with some math applications).

To use this array, you index the array by using an offset for each dimension of the array. You can continue adding offsets for any number of additional dimensions.


Although JScript supports a staggered array, we don't examine the syntax here. It's rather difficult to work with staggered arrays, and there are very few cases in which they are useful and necessary.

  • + Share This
  • 🔖 Save To Your Account