Reputation: 4339
I have a mutable class that I'm using as a key to a generic dictionary. Two keys should be equal only if their references are equal. From what I've read, in this case, I don't need to override Equals, GetHashCode , or implement IEqualityComparer.
Is this correct?
Upvotes: 7
Views: 4174
Reputation: 3915
For anybody using .Net 5 or later it comes with a ReferenceEqualityComparer class that you can pass to the dictionary's constructor. This means you don't need to worry about someone overriding GetHashCode and Equals in the future.
Upvotes: 0
Reputation: 27384
Yes you are correct doing a == comparison (or .Equals) on two objects compares their references if no other overload is specified.
String s = "a";
object test1 = (object)s;
object test2 = (object)s;
Debug.Assert(test1.Equals(test2));
Upvotes: -1
Reputation: 16938
I'll add on to what everyone else has said here (yes) but with one more point that no one seems to have mentioned here.
When using generic collections (Dictionary, List, etc) you can override IEquatable to provide a type specific version that can do your comparison without boxing or up/down casting. These generic collections will use this overload when present to do comparisons and it can be a bit more efficient.
As noted in the docs, when implementing IEquatable you still need to override Equals/Hashcode from Object.
Upvotes: 1
Reputation: 16891
As everyone else pointed out already, yes, you are correct. In fact, you definitely do not want to override the equality members if your type is mutable (it has setters). But, if you want to have equality checking which uses values in your type, you can make your type immutable (like String
) by ensuring that there are no setters (only the constructor sets values). Or use a struct
.
Upvotes: 0
Reputation: 630459
Yes, this is correct. As long as you don't override, reference is the default comparison.
Upvotes: 1
Reputation: 564451
Yes. The default comparison operation in System.Object uses reference equality. If this behavior is what you want, the defaults should work fine.
Upvotes: 16