Search code examples
c#arraysmultidimensional-arraypointindices

Eliminating temp var use when accessing a multidimensional array element


Is there a way to address array object's field with its coordinates in one line?

I have this array: Tile[,] Tiles. Whenever I need to change one of the tiles and I know the indices beforehand, I just do it like this: Tiles[1, 2] = new Tile(args);.

But when I have to calculate them, it looks like this:

Point p = GetTargetTileIndices(args);
Tiles[p.X, p.Y].someField = 127;

Storing tile's indices each time in a temp variable gets confusing and sometimes hard to read. Is there a way to get the indices as Point or something else and work with target array element in one line?


UPD: It is now clear to me that doing…

var tile = GetTile(point);
tile.field = value;

…does not change the tile in the array, but…

GetTile(point).field = value;

…does!


Solution

  • Create a GetTargetTile helper method... just like your GetTargetTileIndices but instead of a Point it returns the actual Tile