I have this code here:
int[] jj = new int[5] {5,6,7,8,9};
byte oo = 0;
foreach (int g in jj) {
jj[oo] = oo;
Console.WriteLine(g+" "+jj[oo]);
++oo;
}
As you can see, not only am i printing each item in the loop but I am also assigning different values to each item inside th eforeach loop.
As the output shows, the avlues do change and get displayed trough jj[oo] but the foreach loop still takes the old values and puts them in the "g".
This is perfectlty reasonable since the foreach loops purpose is not to change values considering the looping variable is readonly as well.
But I am trying to understand how is this effect achieved? How does the "G" stoill take the old vbalues?
Uday DodiyaPosted Aug 8, 2022, 4:52 AM
Sachin SinghPosted May 23, 2022, 6:58 PM
sorry, couldn't understand the question last time.
So, you are asking, how does foreach remember old values?
It doesn't remember, it just doesn't change the value of the current iterating item.
That is why they are called (read-only move next) iterators.
They just iterate through the values.
You can think of foreach as , Give me the next thing if there is still something in the box.
Now, the root cause,
you are able to use foreach over an array, because in c# list and array inherits from IEnumerable. So, they become iterative blocks.
As long as you are iterating in the block, your container is just an IEnumerable and not an actual array.
For example, IEnumerable will not allow you to add or delete anything, means Enumerable doesn't have any method like Add or Remove.
On the other hand List and ArrayList have (Array doesn't have Add/Remove because they are not generic means they have fixed length, but it is out of context for your question.) . But even if List has Add/Remove methods, you can't add/remove anything as long as you are in the iterating block.
Please give it a try and you will get
"
Unhandled Exception:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
"
error.
So, now i think your doubt should be clear.
Note:- If you are now thinking about IEnumerators (not IEnumerable) then they do remember the state but not the values, with IEnumerator we use while loop and MoveNext() method, not foreach.
Muhammad Imran AnsariPosted May 23, 2022, 6:51 PM
Erik MovsesyanPosted May 23, 2022, 5:41 PM
Muhammad Imran AnsariPosted May 23, 2022, 12:59 PM
Sachin SinghPosted May 23, 2022, 5:28 AM
Asma KhalidPosted May 23, 2022, 5:01 AM
Code is working fine. Data is being assigned to the list insode foreachloop. Kindly, detail the issue you are facing tin the assignment?
Thanks & Regards,
Asma Khalid