4

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?

zajke
  • 1,675
  • 2
  • 12
  • 13

2 Answers2

4

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

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
3

Foreach loop iterates over IEnumerable objects..

Internally the above code becomes

using(var enumerator=N.GetEnumerator())
while(enumerator.MoveNext())
{
    enumerator.current=new SomeClass();//current is read only property so cant assign it
}

As stated above in comment current property is a read only property of IEnumerator..So you cant assign anything to it

Anirudha
  • 32,393
  • 7
  • 68
  • 89