I have this code:
private readonly string[,] sSOMETHING = new string[,]
{
{"ONE", "TWO", "THREE"},
{"FOUR", "FIVE", "SIX"}
};
...
foreach (string[] sELSE in sSOMETHING)
{
...
}
I get an error in the foreach that it cannot convert string to string[] when it's obvious the sSOMETHING is an array. Why doesn't it recognize the string array as an array? Do foreach have problems with multidimentional arrays?
2 Answers 2
You are creating 2D array, not the jagged array of array. Change declaration to the following:
private readonly string[][] sSOMETHING = new string[][]
{
new []{"ONE", "TWO", "THREE"},
new []{"FOUR", "FIVE", "SIX"}
};
1 Comment
Compiler is rightly complaining. To use the foreach syntax you would either need to convert it to array of arrays (string[][]) or access it using for loop by getting its dimensions:
Use the below syntax to access all the elements in the multi-dimensional array as if it was flattened
foreach (string sELSE in sSOMETHING) {
Console.Write(sELSE);
}
or use something like
for (int i = 0; i < sSOMETHING.GetLength(0); ++i) {
for (int j = 0; j < sSOMETHING.GetLength(1); ++j) {
Console.Write(sSOMETHING[i, j]);
}
}