Initialize two-dimensional arrays 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 another set of 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 Label controls.

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

The code simply loops through the Label controls in the array and sets their Text properties to a blank string.

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

Download Example   Follow me on Twitter   RSS feed   Donate

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

One Response to Initialize two-dimensional arrays in C#

  1. Pingback: Initialize a Dictionary in C# - C# HelperC# Helper

Leave a Reply

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