Foreach vs for loop in C#. Creation of new object is possible in for loop, but not possible in foreach loop

c#, for-loop, foreach

Solution

`foreach` iteration loops are known as 'read-only contexts.' You cannot assign to a variable in a read-only context.

For more info: http://msdn.microsoft.com/en-us/library/369xac69.aspx

Problem

I have always wonder why you can create new object of class 'SomeClass' in for loop, but you can't do the same in foreach loop. The example is bellow: ``` SomeClass[] N = new SomeClass[10]; foreach (SomeClass i in N) { i = new SomeClass(); // Cannot assign to 'i' because it is a 'foreach iteration variable' } for (int i = 0; i < N.Length; i++) { N[i] = new SomeClass(); // this is ok } ``` Can anyone explain me this scenario?

Original source

Related problems