473,772 Members | 2,965 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overriding the add method of a generic dictionary

I have a generic dictionary (lets call ChildCollection ). I would like
to ensure that whenever a child is added to this collection
(SomeParent.Chi ldren.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.Collecti ons.Generic.Dic tionary<Tkey, TValis not virtual. Can
anyone offer some advice on how to accomplish this. I would like to
avoid implementing all methods of the IDictionary<TKe y, TVal>
interface, just to append some code to the add method.

Your help is appreciated.

Feb 27 '07 #1
5 13320
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<st ring, stringmyDict = new MyDictionary<st ring,
string>();
myDict.Add("KEY ", "VALUE");
}
<mm******@gmail .comha scritto nel messaggio
news:11******** **************@ k78g2000cwa.goo glegroups.com.. .
>I have a generic dictionary (lets call ChildCollection ). I would like
to ensure that whenever a child is added to this collection
(SomeParent.Chi ldren.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.Collecti ons.Generic.Dic tionary<Tkey, TValis not virtual. Can
anyone offer some advice on how to accomplish this. I would like to
avoid implementing all methods of the IDictionary<TKe y, TVal>
interface, just to append some code to the add method.

Your help is appreciated.

Feb 27 '07 #2
Laura T. <LT@NOWHERE.COM wrote:
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,T 2though.

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

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 27 '07 #3
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?

On Feb 27, 12:36 pm, Jon Skeet [C# MVP] <s...@pobox.com wrote:
Laura T. <L...@NOWHERE.C OMwrote:
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,T 2though.

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

--
Jon Skeet - <s...@pobox.com >http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Feb 27 '07 #4
<mm******@gmail .comwrote:
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,Va nd proxy
all calls to that, just doing the extra bit first in Add.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 27 '07 #5
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.

"Jon Skeet [C# MVP]" <sk***@pobox.co mha scritto nel messaggio
news:MP******** *************** *@msnews.micros oft.com...
Laura T. <LT@NOWHERE.COM wrote:
>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,T 2though.

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

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Feb 28 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2034
by: Jasper Kent | last post by:
I'm trying to do the equivalent of using typedefs with templates in C++ to avoid long instantiation names. I can do this okay: using BigDictionary = System.Collections.Generic.Dictionary<int, System.Collections.Generic.Dictionary<int, string>>; class MyClass {
9
6819
by: Paulustrious | last post by:
Is it possible to override the behaviour of a dictionary if an object is not found? string ss=null; Dictionary<string, string> dict = new Dictionary<string, string>(); // method 1 try { ss = dict; }
13
16903
by: Harold Howe | last post by:
Is it possible to override a specific instance of a virtual, generic method? IE: using System; class Base { public virtual void Test<U>(U u) { Console.WriteLine("Base.Test {0}, u); }
8
3750
by: Kenneth Baltrinic | last post by:
When one overrides the Equals() method of an object, one is supposed to override GetHashCode() as well and this makes good sense. But I have seen lots of people who do this and do not override the == and != opperators. Am I missing something or when would one want to have different implementations for Equals and ==? --Ken
5
2285
by: Metaman | last post by:
I'm trying to write a generic method to generate Hashcodes but am having some problems with (generic) collections. Here is the code of my method: public static int GetHashCode(object input) { try { Type objectType = input.GetType(); PropertyInfo properties = objectType.GetProperties();
7
3794
by: Bill Woodruff | last post by:
I've found it's no problem to insert instances of named delegates as values into a generic dictionary of the form : private Dictionary<KeyType, DelegatemyDictionary = new Dictionary<KeyType, Delegate); using the standard .Add method of the Dictionary, passing in the name of the delegate instance for the value. private void myMethodBody()
2
1380
by: Kevin Blount | last post by:
I have a situation where I think I'm calling a method too quickly, but I'm not sure a) how to prove that theory and b) slow it down if I'm right. Here's the code: CODEFILE.ASPX.CS public void updateCookie(string cookieName, string cookiePairName, string cookiePairValue) { if (Request.Cookies != null) { string currentCookie = Request.Cookies.Value; currentCookie += "&" + cookiePairName + "=" + cookiePairValue;
3
1756
by: Otis Mukinfus | last post by:
I've been wrestling with this for a while and can't figure it out. I have a generic method with the following signature: //this compiles OK public abstract class DataMethod { public abstract T Select<T>(); }
2
6289
by: =?Utf-8?B?RGF2aWQgTW9ycmlz?= | last post by:
I am trying to create a nested Dictionary and get an error that seems odd to me. Here is my declaration: private IDictionary<Guid, IDictionary<Guid, string>> myNestedDictionary = new Dictionary<Guid, Dictionary<Guid, string>>(); I get an error unless I nest a Dictionary and not an IDictionary: Error 3 Cannot implicitly convert type
0
9620
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10104
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9912
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6715
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.