Modify Struct variable in a Dictionary

The indexer will return a copy of the value. Making a change to that copy won’t do anything to the value within the dictionary… the compiler is stopping you from writing buggy code. If you want to do modify the value in the dictionary, you’ll need to use something like:

// Note: copying the contents to start with as you can't modify a collection
// while iterating over it
foreach (KeyValuePair<string, MapTile> pair in tilesData.ToList())
{
    MapTile tile = pair.Value;
    tile.bgFrame = tile.bgFrame >= tile.bgAnimation ? 0 : tile.bgFrame + 1;
    tilesData[pair.Key] = tile;
}

Note that this is also avoiding doing multiple lookups for no good reason, which your original code was doing.

Personally I’d strongly advise against having a mutable struct to start with, mind you…

Of course, another alternative is to make it a reference type, at which point you could use:

// If MapTile is a reference type...
// No need to copy anything this time; we're not changing the value in the
// dictionary, which is just a reference. Also, we don't care about the
// key this time.
foreach (MapTile tile in tilesData.Values)
{
    tile.bgFrame = tile.bgFrame >= tile.bgAnimation ? 0 : tile.bgFrame + 1;
}

Leave a Comment