开发者

Dictionary class in C# - Equality of two object

开发者 https://www.devze.com 2023-02-02 16:32 出处:网络
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 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 anothe开发者_运维技巧r 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


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.


Chances are you haven't overridden GetHashCode in a manner consistent with Equals.

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

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

Another possibility is that you haven't actually overridden Equals, but overloaded it by adding a new signature, e.g.

public bool Equals(Class1 other)

In general, to provide a "natural" value equality comparison you should:

  • Override Equals(object)
  • Override GetHashCode
  • Strongly consider implementing IEquatable<T>
  • Consider overloading == and !=


You probably did not override GetHashcode in your class. When you override Equals you must override GetHashcode as well, else Dictionary won't work for you.


Make certain Class1 overrides GetHashCode(). The return from that method is the first thing checked when comparing equality. The default implementation is unique for each object.


Did you override GetHashCode as well ? Can you display the implementation of the Equals method ?


Did you override the GetHashCode either?


You need to override GetHashCode as well, but also don't forget that you may need to pass in a custom Comparer to the Dictionary constructor as well as pointed out in this SO question

0

精彩评论

暂无评论...
验证码 换一张
取 消