Menu
Coddy logo textTech

Declaring and Initializing 2D

Part of the Logic & Flow section of Coddy's C# journey — lesson 2 of 66.

A 2D array in C# can be created using jagged arrays, which are arrays of arrays, allowing you to store data in a grid-like structure.

To create a jagged array of integers with 3 rows and 4 columns:

int[][] grid = new int[3][];
grid[0] = new int[4];
grid[1] = new int[4];
grid[2] = new int[4];

The above code creates a 2D array that looks like this (all elements initialized to 0):

[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

Initialize a jagged array with values:

int[][] matrix = new int[2][];
matrix[0] = new int[] {1, 2, 3};
matrix[1] = new int[] {4, 5, 6};

This creates a 2D array with 2 rows and 3 columns, containing the values:

[1, 2, 3]
[4, 5, 6]

To get the number of rows and columns:

int rows = matrix.Length;           // Returns 2
int columns = matrix[0].Length;     // Returns 3 (for the first row)

Accessing elements in a 2D array requires two indices: one for the row and one for the column.

Assign a value to a specific position (row 1, column 2):

grid[1][2] = 42;

Read a value from a specific position (row 0, column 3):

int value = grid[0][3];

Remember that array indices start at 0, so the valid ranges are:

  • Rows: 0 to 2 (for a 3-row array)
  • Columns: 0 to 3 (for a 4-column array)

If you try to access an element outside these ranges (like grid[3][2]), you'll get an IndexOutOfRangeException.

Cheat sheet

Create a jagged array (2D array) in C#:

int[][] grid = new int[3][];
grid[0] = new int[4];
grid[1] = new int[4];
grid[2] = new int[4];

Initialize with values:

int[][] matrix = new int[2][];
matrix[0] = new int[] {1, 2, 3};
matrix[1] = new int[] {4, 5, 6};

Get dimensions:

int rows = matrix.Length;           // Number of rows
int columns = matrix[0].Length;     // Number of columns in first row

Access elements using two indices [row][column]:

grid[1][2] = 42;        // Assign value
int value = grid[0][3]; // Read value

Array indices start at 0. Accessing out-of-range indices throws IndexOutOfRangeException.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow