What is 2D Array in C#: Definition and Example
2D array in C# is like a table with rows and columns, storing data in a grid format. It is declared using a comma inside square brackets, for example, int[,] matrix = new int[3,4];, where 3 is the number of rows and 4 is the number of columns.How It Works
Think of a 2D array as a chessboard or a spreadsheet where you have rows and columns. Each cell in this grid holds a value, and you can access any cell by specifying its row and column numbers.
In C#, a 2D array is stored in memory as a single block, but you use two indexes to get or set values. The first index is the row number, and the second is the column number. This makes it easy to organize data that naturally fits into a grid, like a calendar or a game board.
Example
This example creates a 2D array of integers with 2 rows and 3 columns, fills it with values, and prints each value with its position.
using System; class Program { static void Main() { int[,] matrix = new int[2, 3]; // Assign values matrix[0, 0] = 1; matrix[0, 1] = 2; matrix[0, 2] = 3; matrix[1, 0] = 4; matrix[1, 1] = 5; matrix[1, 2] = 6; // Print values for (int row = 0; row < 2; row++) { for (int col = 0; col < 3; col++) { Console.WriteLine($"matrix[{row},{col}] = {matrix[row, col]}"); } } } }
When to Use
Use a 2D array when you need to store data in a grid-like structure, such as a game board (like tic-tac-toe), a seating chart, or a matrix for math calculations. It helps organize related data in rows and columns, making it easier to access and manipulate.
For example, if you want to track scores for multiple players across several rounds, a 2D array can hold all scores in one place, where rows represent players and columns represent rounds.
Key Points
- A 2D array stores data in rows and columns like a table.
- Access elements using two indexes: row and column.
- Useful for grid-based data like games, tables, or matrices.
- Declared with a comma inside square brackets:
int[,].