What is the method for initializing a two-dimensional array in C#?
In C#, there are several methods available to initialize a two-dimensional array.
- Initialize array elements one by one using a loop.
int[,] array = new int[3, 4];
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = i + j;
}
}
- Initialize array elements using array initializer.
int[,] array = new int[,]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
- Initialize array elements using simplified array initializer.
int[,] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
The first method is suitable for cases where array elements need to be initialized based on a specific logic, while the last two methods are suitable for cases where the specific values of array elements are already known.