Take the 2-minute tour ×
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.....

share|improve this question
... and the question is... –  Austin Salonen Feb 2 '12 at 22:43
Sorry for confusion I will add more deetails –  Bug Feb 2 '12 at 22:44
In previous question, you was given an answer with documentation. There you will find answer for this question to. –  Damian Leszczyński - Vash Feb 2 '12 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 –  DJ KRAZE Feb 2 '12 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... –  Thomas Levesque Feb 2 '12 at 22:45

2 Answers 2

up vote 3 down vote accepted

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];
share|improve this answer
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? –  Bug Feb 2 '12 at 22:45
@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. –  JaredPar Feb 2 '12 at 22:46
sounds like someone needs to read up more on Coding Loops, Iterators etc.. –  DJ KRAZE Feb 2 '12 at 22:46
@downvoter, care to explain? –  JaredPar Feb 2 '12 at 22:49
sorry for this dumb question. I will do more research before I post next question. –  Bug Feb 2 '12 at 22:53

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();
share|improve this answer

Your Answer


