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

I am always wondering why you can create a new object of the SomeClass class in a for loop, but you cannot do the same in foreach .

Example below:

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 someone explain this scenario to me?

+4
source share
2 answers

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

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

+4
source

The Foreach loop iterates over IEnumerable objects.

Internal code above

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

As stated in the comment above, the current property is a read-only property of IEnumerator .. So you cannot assign something to it

+3
source

Source: https://habr.com/ru/post/1492595/


All Articles