Initialize an array of arrays in C#

The example Initialize a two-dimensional array 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)
{
for (int r = 0; r < 3; r++)
{
for (int c = 0; c < 3; c++)
{
Squares[r][c].Text = "";
}
}
}

There are a couple of differences between this example and the earlier one that uses a two-dimensional array. The most obvious difference is the syntax. The earlier example accessed an array entry as in Squares[r, c]. This example accesses the corresponding entry as in Squares[r][c].

A less obvious difference is that the rows in this example's array do not all need to contain the same number of items. Each row holds an array of Labels but the declaration doesn't indicate that each of those much 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, the code cannot assume each that each row holds three items. Instead of using the earlier code to clear the Labels, the program would need to use the following code to clear every Label in each row.

for (int r = 0; r < Squares.Length; r++)
{
for (int c = 0; c < Squares[r].Length; c++)
{
Squares[r][c].Text = "";
}
}

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.