3

Hi i have a simple bit of code where i have a private field of a dictionary, and a property that exposes it via get.

But i can still insert to this dictionary from other classes, and was wondering how i can prevent that so i can only insert to the dictionary via the field within the class it is defined and not via the property that exposes it?

This is my field/property code:

    private Dictionary<UnitType, Entity> _systems;
    public Dictionary<UnitType, Entity> Systems => _systems;

In some other class i am still able to do MyClass.Systems.Add() which i want to prevent.

Is this possible ?

WDUK
  • 1,412
  • 1
  • 12
  • 29
  • 1
    Keep your Dictionary in a private property or field. Use a second (public) property to expose the dictionary wrapped in a [ReadOnlyDictionary](https://msdn.microsoft.com/en-us/library/gg712875(v=vs.110).aspx) –  Jun 27 '18 at 22:42
  • @elgonzo so my read only dictionary casts the dictionary every time i call it right? – WDUK Jun 27 '18 at 22:44
  • No. I said "...dictionary **wrapped** in a ReadOnlyDictionary". Look up the documentation for ReadOnlyDictionary (i linked in my first comment). Just casting the dictionary to `IReadOnlyDictionary` would still allow it to be cast as normal writable `Dictionary` again... –  Jun 27 '18 at 22:45
  • However, if you just want Intellisense stop bugging you with also suggesting modifying methods, then of course you can forego using ReadOnlyDictionary wrapper and just cast your dictionary as `IReadOnlyDictionary`. –  Jun 27 '18 at 22:50
  • Okay thank you for the help, yeah just cleaning up the intellisense is sufficient for this project :) – WDUK Jun 27 '18 at 22:51

1 Answers1

3

How about this:

private Dictionary<UnitType, Entity> _systems;
public IReadOnlyDictionary<UnitType, Entity> Systems => _systems;

This would expose only readonly capabilities of the _systems dictionary in the public property.

WIMP_no
  • 519
  • 6
  • 7