Override Dictionary.Add

Phil picture Phil · Jun 6, 2011 · Viewed 18.7k times · Source

I need to know how to override the Add-method of a certain Dictionary in a certain static class. Any suggestions?

If it matters, the dictionary looks like this:

public static Dictionary<MyEnum,MyArray[]>

Any suggestions?

Answer

CodesInChaos picture CodesInChaos · Jun 6, 2011

You can't override the Add method of Dictionary<,> since it's non virtual. You can hide it by adding a method with the same name/signature in the derived class, but hiding isn't the same as overriding. If somebody casts to the base class he will still call the wrong Add.

The correct way to do this is to create your own class that implements IDictionary<,> (the interface) but has a Dictionary<,> (the class) instead of being a Dictionary<,>.

class MyDictionary<TKey,TValue>:IDictionary<TKey,TValue>
{
  private Dictionary<TKey,TValue> backingDictionary;

  //Implement the interface here
  //Delegating most of the logic to your backingDictionary
  ...
}