Override Dictionary.Add

.net, c#, dictionary, overriding, windows-phone-7

Solution

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

Problem

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?

Original source