I’m creating a class which populates a dictionary as a private member. I want to expose the values of the dictionary without exposing the dictionary itself (in a read-only fashion.) I can easily make a property to expose _dictionary.Keys, but how can I overload [] so that MyClass[key] returns _dictionary[key]?
I think I may need to implement an interface, but I’m not sure which one…
I’m pretty sure this is what you’re after:
If you want to implement an interface to indicate to client code that your class can be accessed by an index of type
TKey, the closest match (that I’m aware of) isIDictionary<TKey, TValue>.Unfortunately,
IDictionary<TKey, TValue>has a whole bunch of members that violate your read-only requirement, which means you would have to explicitly implement lots of members only to throw aNotImplementedException(or somesuch) when they’re called: namely, the setter forthis,Add,Clear, andRemove.Maybe there’s a different interface that would be more appropriate for this purpose (something like
IReadOnlyDictionary<TKey, TValue>?); I just haven’t come across it.You could also write your own interface, of course, if you intend to have multiple classes that offer functionality similar to this.