C
C#4w ago
Attikitty

✅ How does dictionary.ContainsKey() work?

i have a class that implements IEquatable and ICompareable (i think only iequatable is needed for this but i could do both so i did), yet when I try and use it as a key it doesn't seem to work. here is a pretty much what I have, tho i can send the actual code if needed
c#
ItemType item1 = ...
ItemType item2 = ...

var dict = new Dictionary<ItemType, int>();
dict.Add(item1, 3); // doesnt matter what the value is rn

console.write(item1.Equals(item2)); // returns true
console.write(dict.ContainsKey(item2)); // returns false???
c#
ItemType item1 = ...
ItemType item2 = ...

var dict = new Dictionary<ItemType, int>();
dict.Add(item1, 3); // doesnt matter what the value is rn

console.write(item1.Equals(item2)); // returns true
console.write(dict.ContainsKey(item2)); // returns false???
what else do I need to do to make this function?
7 Replies
Jimmacle
Jimmacle4w ago
did you also implement GetHashCode (properly)?
Attikitty
AttikittyOP4w ago
no i didn't i assume that's needed? thxs
Jimmacle
Jimmacle4w ago
dictionaries use that first to determine if two objects may be equal
Attikitty
AttikittyOP4w ago
is gethashcode part of iequatable?
Jimmacle
Jimmacle4w ago
no, it's a virtual method of object
Attikitty
AttikittyOP4w ago
ah ok thxs how do I close this and mark as solved? or do i not need to do that
MODiX
MODiX4w ago
If you have no further questions, please use /close to mark the forum thread as answered

Did you find this page helpful?