0

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?

asked Apr 10, 2013 at 10:47

2 Answers 2

8

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"}
};
answered Apr 10, 2013 at 10:49
Sign up to request clarification or add additional context in comments.

1 Comment

...or, iterate the "old-fashioned" way :)
2

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]);
 }
}
answered Apr 10, 2013 at 10:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.