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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With