Quantcast
Channel: 2,000 Things You Should Know About C# » foreach
Viewing all articles
Browse latest Browse all 10

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

$
0
0

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));
                d.Age++;
                Console.WriteLine(d);
            }

1121-001


Filed under: Statements Tagged: C#, foreach, Statements

Viewing all articles
Browse latest Browse all 10

Trending Articles