Initialize an array of arrays in C#


The example Initialize two-dimensional arrays in C# explains how to initialize a two-dimensional array. An array of arrays is somewhat similar to a two-dimensional array but with some syntax differences.

The following code shows how this example declares and initializes its array of arrays holding Label controls.

// An array of arrays holding the squares.
private Label[][] Squares;

// Initialize the array of arrays holding the squares.
private void Form1_Load(object sender, EventArgs e)
    Squares = new Label[][]
        new Label[] { lblSquare00, lblSquare01, lblSquare02},
        new Label[] { lblSquare10, lblSquare11, lblSquare12},
        new Label[] { lblSquare20, lblSquare21, lblSquare22},

The code declares the array of arrays at the class level so it is accessible to all methods. The form’s Load event handler then initializes it.

The Squares variable itself holds a Label[][]. This is actually an array, each element of which is a Label[].

The braces enclose the object’s contents separated by commas. Each of the elements is also an array, in this case containing Label controls. Their contents are also surrounded by braces and separated by commas.

The following code shows how the program clears the Labels.

// Clear all squares.
private void btnClear_Click(object sender, EventArgs e)
    foreach (Label[] array in Squares)
        foreach (Label label in array) label.Text = "";

There are a couple of differences between this example and the earlier one that uses a two-dimensional array. The previous example used a foreach loop to loop through all of the Label controls in the two-dimensional array. This version can’t do that because the variable Squares holds arrays not Label controls. Instead this version loops through Squares to get its arrays. It then loops through each of those arrays to access the Label controls it contains.

To access a specific Label directly, the previous example would have uses syntax similar to Squares[r, c]. In contrast, the new version would use syntax similar to Squares[r][c].

A less obvious difference between the two approaches is that this example’s arrays do not all need to contain the same number of items. Each row holds an array of Label controls but the declaration doesn’t indicate that each of those must be the same size. For example, the following code would also initialize the array.

Squares = new Label[][]
    new Label[] { lblSquare00, lblSquare01, lblSquare02},
    new Label[] { lblSquare10, lblSquare11},
    new Label[] { lblSquare20},

In this case, however, each row doesn’t hold three items.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in arrays, syntax and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *