0

I have a dictionary that I would like to pass externally through a property but I would like to limit some features like the clear method. Here's the code that i've implemented.

// dictionary private declaration inside the class
private Dictionary<int, string> _value = new Dictionary<int, string>();

// here's the property declaration for access the dictionary outside the class
public new Dictionary<int, string> Value
{
    get
    {
        return _value;
    }
    set
    {
        // here is where i'd like to avoid some dictionary features like clear() and give only the opportunity to add or change existing values
        _value = value;
    }
}

It’s possible through the “set” of this property to limit some of the features of the dictionary? Maybe using a switch or an if statement?

  • 5
    `Dictionary` implements a few different interfaces, such as `IReadOnlyDictionary` - you could return it as one of those (assuming any of them fulfill your criteria) – UnholySheep Jun 14 '20 at 19:49
  • Alternatively, you use the [decorator pattern](https://en.wikipedia.org/wiki/Decorator_pattern) and return a dictionary wrapper such as the one from [this answer](https://stackoverflow.com/a/9490016/3744182) to [Code Contracts: Ensures Unproven & Requires Unproven](https://stackoverflow.com/q/7419134/3744182) and disable the unwanted methods in the wrapper by overriding them and throwing exceptions. – dbc Jun 21 '20 at 16:48

1 Answers1

2

There are a ReadonlyDictionary that acts as a wrapper around a dictionary, and a corresponding IReadOnlyDictionary interface.

If you are on .Net core 3 there is also an ImmutableDictionary if the dictionary never needs to be changed.

If this is to coarse grained, you can always create your own wrapper that works however you want it to.

JonasH
  • 28,608
  • 2
  • 10
  • 23