0
int[][] myArray = new int[10][];

foreach (int[] eachArray in myArray) {
eachArray = new int[2]
}

I believe it should create an array that is

{ 0 , 0 }
{0 , 0}
.........

Jagged array is so confusing.....

8
  • Sorry for confusion I will add more deetails Commented Feb 2, 2012 at 22:44
  • In previous question, you was given an answer with documentation. There you will find answer for this question to. Commented Feb 2, 2012 at 22:44
  • Arrays are not confusing.. please post an actual question not just code that you expect us to know what it is you're thinking or having issues with..thanks Commented Feb 2, 2012 at 22:45
  • Jagged arrays are not that confusing, if you think of it as an array of arrays: it behaves just like any other array, but its items are arrays too... Commented Feb 2, 2012 at 22:45
  • If jagged arrays are confusing, use a List<List<int>> instead. It has also the advantage that it's resizable without overhead(copying into another array). Commented Feb 2, 2012 at 23:06

2 Answers 2

4

This will not create the jagged array you are looking for. It's attempting to assign a new int[2] instance to the iteration variable, not to the slot in the original array. This won't even compile as the iteration variable is treated as readonly by the compiler

The way to do this is with a for loop

for (var i = 0; i < myArray.Length; i++) {
  myArray[i] = new int[2];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, however should I always use that approach? It seemed using for loop is quite ugly to me... Is there any prettier way to do it?
@user1143720 the for loop is the standard way of doing it. It can be done with a full blown initializer but that requires initializing the entire array inline.
sorry for this dumb question. I will do more research before I post next question.
3

Assigning to loop variables inside foreach loop is not allowed. You need a regular for loop with a counter, or you can try something slightly fancier:

int[][] myArray = Enumerable.Range(0, 10).Select(i => new int[2]).ToArray();

Comments

Your Answer

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.