Thursday, February 5, 2015

Readonly local variable cannot be used as an assignment target

This error rears its head when you try to edit the gunk inside of a foreach loop in C#, especially so if you try to replace the variable for the child at hand in a loop step. If you need to hand each child out to a method elsewhere to reshape it and expect to return an object of the same type as the object that needs editing you, again, may not just overpower the old with the new. You have to either incrementally create a new list as you loop through the old list, or, in the case of just doctoring up one match, you can do something like this:

int counter = 0;
int positionOfInterest = 0;
User alteredUser = null;
foreach (User user in _users)
{
   if (user.Username == e.Keys[0].ToString())
   {
      alteredUser = UserUpdater.Update(user, GroupId, e.OldValues, e.NewValues,
            MyRepository);
      positionOfInterest = counter;
   }
   counter++;
}
if (alteredUser != null)
{
   MyRepository.UpdateUser(alteredUser);
   _users[positionOfInterest] = alteredUser;
}

No comments:

Post a Comment