Search code examples
c#ref

Sharing variables between objects / class properties


So I have a "world" object which contains a list of "tiles". I also have a "island" objects which contains certain "tiles" from the "world" objects list of "tiles". For external purposes I want to keep world and island as objects / classes.

I want to be able the change the values of the tiles in the list in world and for those changes to be observed in the tile class and vice versa.

Basically I want:

class World {
    List<Tile> tiles;
}

class Islands {
    // ref here is not syntax
    List<ref Tile> tiles;
}

But the ref is not allowed as a type argument in the list thingy. What is someway I can implement this behaviour while keeping them as close to be objects / class and not have duplicating tiles.


Solution

  • Not 100% clear on your requirements. But, if you want to share tiles, then both World and Island references will see changes in the values of those tiles automatically because they are sharing instances (which must be classes and not structs). This is passive though. If you need something to occur when these changes occur (e.g. telling World or Island to look and pay attention) then implement an event to be raised when the property changes.

    If you need a complete replacement of a tile and want to observe that change then implement a layer of indirection; for example, a TileReference with a Tile property. When that property changes, you can raise an event, and a handler can observe the entirely new tile.