Reputation: 1405
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
Upvotes: 4
Views: 5510
Reputation: 113472
2 possibilities:
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#?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.
Upvotes: 13
Reputation: 2462
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.
Upvotes: 3
Reputation: 56428
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
Upvotes: 3
Reputation: 161012
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.
Upvotes: 4
Reputation: 56984
Did you override GetHashCode as well ? Can you display the implementation of the Equals method ?
Upvotes: 3
Reputation: 1503954
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:
IEquatable<T>
Upvotes: 12