1

I have an interface that requires the square brackets operator to be implemented. The class that inherits from this implements it. However,it also inherits from Dictionary<>, where that same operator is implemented:

public interface IFoo
{
    IBar this[String tFooName] { get; }
}


[Serializable]
public class ConcreteFoo: Dictionary<String, Bar>, IFoo
{
    // Implement interface by calling the dictionary
    public IBar this[String tFooName] { get { return this[tFooName]; } }



    // .... more code ....
}

When I try to use the code, the compiler references the immediate interface that was implemented and says that I cannot assign to it:

MyClass[tKeyStr] = new Bar();

The error is correct. So, I removed my implementation of the IFoo interface and hoped that by inheriting from Dictionary<>, it would be auto-implemented. It has not panned out the way I wanted.

I get the error 'does not implement interface member ...'.

How would I solve this without making the dictionary a private member?? Is there a way?

1 Answer 1

4

Does it really need to derive from Dictionary<string, Bar>? In my experience it's rarely a good idea to derive directly from Dictionary<TKey, TValue>, List<T> etc - only the collections which have been explicitly designed for inheritance (e.g. Collection<T>) usually work well as a fit for inheritance.

Can you not just make your ConcreteFoo have a Dictionary<string, Bar> field instead? You sort of allude to that in your final question, but it's not clear why you're trying to use inheritance instead of composition.

If you really must use inheritance, you can use explicit interface implementation, like this:

IBar IFoo.this[String tFooName] { get { return this[tFooName]; } }

... but I would suggest favouring composition instead.

Sign up to request clarification or add additional context in comments.

3 Comments

My reason is that this object IS a dictionary with a few added methods and fields. I slimmed down the code for brevity.
@MarkP: I would still suggest using composition, but implementing your interface and IDictionary<string, Bar>. This will be nicer over time than subclassing Dictionary<T,U>.
@MarkP: Is it necessary that code which is expecting a Dictionary accept your type just as well? If so, then inheritance is proper. if not, composition is better.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.