#1,121 – Modifying Elements in a Collection Using foreach

Although the iteration variable in a foreach loop is read-only, you can still use the iteration variable to modify the elements of a collection, as long as they are reference-typed.  (Value-typed elements are immutable).  You’re not changing the iteration variable, but rather changing the object that it refers to.

            List<Dog> myDogs = new List<Dog>
                    new Dog {Name = "Kirby", Age = 15},
                    new Dog {Name = "Ruby", Age = 2},
                    new Dog {Name = "Jack", Age = 17}

            foreach (Dog d in myDogs)
                Console.Write(string.Format("{0} / ", d));