Search code examples
c#.netdictionaryreadonlyreadonly-collection

Is there an easy way to have a dictionary-like object that cannot be added to, but whose values can be modified?


Suppose I have a class Composite that is constructed from a dictionary of instruments and weights.

public IReadOnlyDictionary<Instrument, double> Underlyings{ get; private set; } 

public Composite(
    Id id,
    Currency currency,
    Dictionary<Instrument, double> underlyings
    )
{
    Underlyings= underlyings;
}

}

This class is exposed to the client, and I want the client to be able to modify the existing keys' values within Underlyings, but not add new key-value pairs to Underlyings.

Then making Underlyings a ReadOnlyDictionary will not work as the client code will not be able to modify the values for existing keys. So my solution was to take the wrapper around a dictionary from this answer and modify the setter for TValue IDictionary<TKey, TValue>.this[TKey key] such that existing values can be modified. But this seems like a silly solution - is there an easier way than writing a wrapper class to have a dictionary which has modifiable existing key-value pairs, but cannot have new key-value pairs added to it? Apologies for the very simplistic question.


Solution

  • No, there is no standard dictionary that only allows updates. Its all or nothing.

    As you have discovered, you have to create it your own, or find an implementation that is already there. Overriding the Add and this[] property is a solution that might work for you.