views:

169

answers:

1

Let's say I have a class called myclass.

In my code I have two instances of myclass, myclass1 and myclass2. Everything about them is (public and private) properties are identical.

If I try to add both of them to a HashSet will it add both or only one? If it adds both and I don't want it to, can I overidde equals in the myclass definition and the HasSet will know how to use it?

+2  A: 

Short answer, it depends upon your object's Equals method.

Longer answer:

HashSet will use an IEqualityComparer to determine if two objects are equal. If you don't provide one it will use EqualityComparer.Default; which effectively just uses object.Equals(a, b) plus some stuff to avoid boxing value types.

Checking the docs for object.Equals(a, b): It is effectively just performing a.Equals(b) after checking for nulls.

The default implementation of object.Equals(other) is to check for reference equality only (i.e., they are the exact same instance of an object) but you can override this to perform any check you like, such as checking if an ID field is identical. Note, when overriding Equals you also have to override GetHashCode.

If you want to change how HashSet determines equality without altering the object's definition you can provide it a custom IEqualityComparer instead.

KeeperOfTheSoul