Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can indexers be redefined in a Dictionary-inherited class?

I am trying to implement a MultiDictionary: a Dictionary which holds a List in each key.

I want to be able to add elements to the dictionary using the addition assignment operator and indexers :

myMultiDictionary[key] += elementToAdd;

I first created a custom AddableList which inherits from List and overloads the + and - operators, which let's me use the addition assignment operator :

myAddableList += elementToAdd;

MultiDictionary is then a simple inheritance of Dictionary<keyType, AddableList<contentType>>.

I'm having problems with the indexers. I wish to keep the Dictionary inheritance to use the O(1) performance of dictionary keys. However, I have to redefine the indexers to:

  • create an empty list if I create a new key;
  • delete a key if I remove all elements in the list.

How does inheritance work for classes where indexers are already defined? Will my new indexers overwrite all access methods defined in dictionary?

like image 533
Queder Avatar asked Jan 28 '26 02:01

Queder


1 Answers

Since the indexer of Dictionary is not marked as virtual, you cannot really override it. You can only hide it by adding a 'new' keyword to your indexer, but don't do this, anybody could upcast your MultiDictionary to Dictionary and use the indexer of the base class. Best solution for you is, rather than inherit from a Dictionary, your MultiDictionary should implement an interface IDictionary, than hold private Dictionary instance internally in MultiDictionary and redirect all interface implementations without any custom logic to the Dictionary instance. In other words just create Proxy to the Dictionary.

like image 148
Jan Muncinsky Avatar answered Jan 29 '26 16:01

Jan Muncinsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!