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.