Reputation: 4288
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?
Upvotes: 1
Views: 235
Reputation: 1503090
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.
Upvotes: 4