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.