Overriding the add method of a generic dictionary

M

mmurrell

I have a generic dictionary (lets call ChildCollection). I would like
to ensure that whenever a child is added to this collection
(SomeParent.Children.Add(new Child()), the parent of the child object
is set appropriately.

For some reason I would like to understand, the Add method of
System.Collections.Generic.Dictionary<Tkey, TVal> is not virtual. Can
anyone offer some advice on how to accomplish this. I would like to
avoid implementing all methods of the IDictionary<TKey, TVal>
interface, just to append some code to the add method.

Your help is appreciated.
 
L

Laura T.

In C# it does not have to be virtual. You can "hide" (override) public
methods of base classes.

This works. The Add method of MyDictionary will be called.

private class MyDictionary<T1, T2> : Dictionary<T1, T2>
{
public new void Add(T1 key, T2 val)
{
// do something
base.Add(key, val);
}
}

static void Main(string[] args)
{
MyDictionary<string, string> myDict = new MyDictionary<string,
string>();
myDict.Add("KEY", "VALUE");
}
 
J

Jon Skeet [C# MVP]

Laura T. said:
In C# it does not have to be virtual. You can "hide" (override) public
methods of base classes.

That won't help much if anything refers to the dictionary as a plain
Dictionary<T1,T2> though.

Hidden methods are a source of bugs just waiting to happen, IMO. It's
important that you can do it occasionally, but usually because a base
class out of your control has added a method with the same name as your
derived class. I wouldn't recommend using it as a "pseudo-override".
 
M

mmurrell

John and Laura thank you both for your replies.

Laura, I have implemented the solution you suggested and it does
work.

John:

I agree this could be "a source of bugs waiting to happen". What
would be your recommendation as a solution to the problem?
 
J

Jon Skeet [C# MVP]

John and Laura thank you both for your replies.

Laura, I have implemented the solution you suggested and it does
work.

John:

I agree this could be "a source of bugs waiting to happen". What
would be your recommendation as a solution to the problem?

Well, IDictionary<K,V> doesn't actually have many methods - it wouldn't
be hard to have a member which is a "normal" Dictionary<K,V> and proxy
all calls to that, just doing the extra bit first in Add.
 
L

Laura T.

True. But that's the price of inheritance I guess.
You can always abuse the design of you really want to.
Once I did have to use reflection at runtime to "override" some method
implementations because of the abuse.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top