9

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...

2 Answers 2

24

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.

1
  • Thanks! It's hard to search for []. I don't need to go so far as to write my own interface, but thanks for that tip, too. Just the code you gave was everything I need for now.
    – dlras2
    May 18, 2010 at 17:22
4

This is called an Indexer. See http://msdn.microsoft.com/en-us/library/2549tw02.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.