Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary class in C# - Equality of two object

I have a class named Class1 I override its Equals function Now I have an instance of Dictionary And I added an instance of Class1 named OBJ1 to it. I have another instance of Class1 named OBJ2. the code returns true for OBJ1.Equals(OBJ2). But I can't find OBJ2 in dictionary.

Here is pseudo code

Class1 OBJ1 = new Class1(x, y, z);
Class1 OBJ2 = new Class1(a, b, c);
Dictionary<Class1, int> dic1 = new Dictionary<Class1, int>();
dic1.Add(OBJ1, 3);
OBJ1.Equals(OBJ2) -------------> return true
Dictionary.ContainsKey(OBJ2) --------------> return false

why is this happening? any help would be highly welcomed

like image 363
Masoud Avatar asked Nov 26 '22 23:11

Masoud


1 Answers

2 possibilities:

  1. GetHashCode has not been overridden correctly. You might want to take a look at Why is it important to override GetHashCode when Equals method is overriden in C#?
  2. OBJ1 has been mutated after it has been added to the dictionary in a way that impacts its hashcode. In this case, the bucket it is placed in will no longer be correct - ContainsKey will end up hunting for it in a different bucket.

From Dictionary<TKey, TValue>:

As long as an object is used as a key in the Dictionary, it must not change in any way that affects its hash value.

like image 90
Ani Avatar answered Nov 29 '22 11:11

Ani