Search code examples
c#arraysoopencapsulation

Encapsulation of arrays, should I deep copy?


A class has a private array/list. It is encapsuled by only allowing editing through methods like "AddElement".

Now another class needs information about all elements of that array/list.

Passing the reference of the array/list would break the encapsulation. Returning a new array/list but with the same objects would still allow manipulating the objects. Creating a deep copy feels a bit like overkill. Is there a better way?

As an example: In a game, I have multiple units. To put markers on a minimap, the unit's position and unit type is needed by the renderer. The renderer should not be able to change all kinds of properties of the units.

I'm doing this in C#.


Solution

  • Create a new method which will expose only the needed info. Something like:

    public (Point Position, string UnitType) GetUnitInfo()
    {
        return _units.Select(u => (u.Position, u.UnitType));
    }