Can’t modify members because it is a foreach iteration variable, use a for loop

I had a requirement where I received a generic list from a method and needed to iterate through the the list and change a value if certain criteria were met. Initially, I decided to use a foreach statement. However that resulted in a Can’t modify members because it is a ‘foreach iteration variable’ exception. Which makes sense considering that a foreach is actually calling the GetEnumerator() behind the scenes. To learn more about generics and how generics lists work, check out my C# fundamental on that subject. We know that the collection we iterate through must implement the IEnumerable<T> interface and in this case the List collection certainly does. Here is an example of what I tried originally:

foreach (string item in listOfStrings)
{
  if (item.EndsWith("10"))
  {
    //item = "Can't modify members in foreach iteration variable";
    Console.WriteLine("Can't do anything but read the value.");
  }                
}

Instead I realized that it is possible to loop through the values in the list within a for loop. Like this:

for (int i = 0; i < listOfStrings.Count; i++)
{
    if (listOfStrings[i].EndsWith("10"))
    {
        //Can modify members in for loop";
        listOfStrings[i] = 
            "Modifed string number " + i.ToString();
    }
}

The for loop statement does not implement the IEnumerator<T> interface and therefore the values within the list can be searched through and modified.

Download the source




Leave a Comment

Your email address will not be published.