Erik Movsesyan

Erik Movsesyan

  • 2.1k
  • 25
  • 698

foreach loop not assigning values to array variables

May 22 2022 9:03 PM

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?


Answers (6)