Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 587
zajke Avatar asked Mar 23 '23 02:03

zajke


2 Answers

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

like image 123
edtheprogrammerguy Avatar answered Apr 06 '23 08:04

edtheprogrammerguy


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

like image 25
Anirudha Avatar answered Apr 06 '23 09:04

Anirudha