Initialize a two-dimensional array in C#

The example Initialize arrays, lists, and class instances in C# explains how to initialize a one-dimensional array. You can use a similar syntax to initialize multi-dimensional arrays.

Use a new statement to indicate the type of array you are initializing. Follow that by braces enclosing the elements that should be inside the array. Each of those elements represents a row in the array and you should initialize it by using values enclosed in braces.

The following code shows how this example initializes a two-dimensional array of Label controls.

// A 2-D array holding the squares.
private Label[,] Squares;

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

The code declares the Squares variable at the class level so it is available in all methods. The form's Load event handler then initializes the array. The initializer includes three rows, each initialized with three values.

The following code shows how the program uses the array to clear 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 = "";
}
}
}

The code simply loops through the array's rows. For each row, it loops through the row's columns, setting the Labels' Text properties to a blank string.

You can use similar syntax to make even higher-dimensional arrays.

  

 

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.