7

I have class that implements interface as below

class Person : IHuman
{
}

I have created dictionary as below

Dictionary <IHuman, collection<int>> dic = new Dictionary <IHuman, collection<int>>();

Now I add one key value pair as belwow

dic.Add (person, myCollection);

Again when I use containsKey for "same person object and with same HashCode" as below

if (dic.ContainsKey(person))
{
    dic[person] = mynewcollection;
}
else
{
    dic.Add (person, mynewcollection);
}

Here ContainsKey() returns false and creates one more key value pair with same person object.

I wondered how it possible... Please help me to sort out this issue.

3 Answers3

11

Yes, it is possible, but you should override Equals and GetHashCode of your Person class. Otherwise keys (i.e. persons) will be compared by reference. And every new instance will be considered different, even if all fields have same values.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4

It sounds like you're overriding GetHashCode() or Equals incorrectly, basically. We can't really tell without more information - presumably your Person class actually has some code in it.

However, fundamentally this code is daft:

if (dic.ContainsKey(person))
{
    dic[person] = mynewcollection;
}
else
{
    dic.Add (person, mynewcollection);
}

In both cases, the dictionary ends up with an entry with a key of person and a value of mynewcollection... which is exactly the same as you get if you just write:

dic[person] = mynewcollection;

That will add a new entry or overwrite an existing entry as required.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You need to override equals on your person object. See http://msdn.microsoft.com/en-us/library/ms173147.aspx for more info

geedubb
  • 4,048
  • 4
  • 27
  • 38
  • 2
    when using in a dictionary key, it is also explicitly required to override `GetHashCode`. Frankly, they always go together - I think MSDN could phrase that more strongly. – Marc Gravell Nov 23 '12 at 12:56