Alex Rivera | Logout

C# Dictionary issue for reference type as Key

Asked 2012-11-23T12:48:21.490
8

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.

c#
Edit
Report

1 Answer

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.

answered 2012-11-23T12:50:23.587

Your Answer