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.

0

3 Answers 3

12

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.

1
  • 1
    Best answer ! ..
    – Legends
    Jul 8, 2017 at 15:40
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.

1

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

1
  • 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. Nov 23, 2012 at 12:56