C# Dictionary issue for reference type as Key
c#
Solution
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.
Problem
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.