How can I overload the [] operators?
.net, c#, dictionary, interface, operator-overloading
Solution
I'm pretty sure this is what you're after:
public TValue this[TKey key] {
get { return _dictionary[key]; }
}
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) is `IDictionary<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 a `NotImplementedException` (or somesuch) when they're called: namely, the setter for `this`, `Add`, `Clear`, and `Remove`.
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.
Problem
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...