C # dictionary class - Equality of two objects

I have a class called Class1 I redefine its Equals function Now I have a dictionary instance And I added an instance of Class1 named OBJ1 to it. I have another instance of class 1 named OBJ2. The code returns true for OBJ1.Equals (OBJ2). But I can not find OBJ2 in the dictionary.

Here is the 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 appreciated

+4
source share
7 answers

Make class Class1 overrides GetHashCode (). The return from this method is checked first when comparing equality. The default implementation is unique to each object.

+3
source

2 possibilities:

From Dictionary<TKey, TValue> :

As long as the object is used as a key in the Dictionary, this should in no way affect its hash value.

+13
source

Most likely you did not redefine GetHashCode according to Equals .

The GetHashCode contract requires that if OBJ1.Equals(OBJ2) returns true, then OBJ1.GetHashCode() must return the same value as OBJ2.GetHashCode() .

IIRC, you will get a compiler error (or at least a warning) if you override Equals without overriding GetHashCode() .

Another possibility is that you are not really overridden Equals , but overloaded it by adding a new signature, for example

 public bool Equals(Class1 other) 

In general, to ensure a "natural" comparison of equality of values, you need to:

  • Override Equals (Object)
  • Override GetHashCode
  • Strictly consider implementing IEquatable<T>
  • Consider overload == and! =
+12
source

You probably did not override GetHashcode in your class. When you override Equals, you must also override GetHashcode, otherwise the dictionary will not work for you.

+4
source

Have you redefined GetHashCode too? Can you display the implementation of the Equals method?

+3
source

Have you redefined GetHashCode ?

+3
source

You must also override GetHashCode , but also remember that you may need to pass the Dictionary constructor to your custom Comparer, as well as as indicated in this SO Question

+3
source

Source: https://habr.com/ru/post/1334230/