I have a simple class which has boolean field:
public struct Foo { bool isAvailable; }
Now I have a List of foos:
List < Foo > list = new List< Foo >();
Later on I enumerate each foo in the list and try to update its isAvailable field:
foreach(Foo foo in list) {
foo.isAvailable = true;
}
But the above code never updates the list. What am I doing wrong here and what’s its remedy.
It’s because
Foois a mutable struct.When you fetch the value from the list, it’s making a copy – because that’s how value types behave. You’re changing the copy, leaving the original value unchanged.
Suggestions:
While you could change your code to iterate over the list in a different way and replace the value each time, it’s generally a bad idea to do so. Just use a class… or project your list to a new list with the appropriate values.
Original answer, when Foo was a class
It should work fine. For example, here’s a short but complete program which does work:
Try to adapt your current code to a similar short but complete program which doesn’t work, post that, and we can work out what’s going on.