I'm working on a simple application with a few classes. This all started when I wanted to use the Remove
method on a List<Car>
. This method requires that you override the Equals
and the GetHashCode
methods for the Car
type. In this situation, I decided to implement an ID property on the Car
class. That way, my Equals
method simply checks for ID equality, and my GetHashCode
method returns base.GetHashCode()
.
Is this a good approach, or is implementing a GUID for a small class too heavy-handed? There wouldn't be any need for it without the reasons I explained above. The only requirement for uniqueness for this Car type is that it be unique within the List<T>
collection to which it belongs. But adding the GUID property seemed like the quickest way around the GetHashCode
mess. BTW, there are no int properties on my Car type.
Instead of implementing Equals and GetHashCode just use RemoveAll
:
myList.RemoveAll(x => x.ID == myCar.ID);
This allows you to specify a predicate that indicates what items should be removed instead (it doesn't matter that you are only removing one item).
Implementing Equals
and GetHashCode
in the way you describe strikes me as extremely dodgey - if your Equals
implementation returns true
then your GetHashCode
method needs to return the same value so that those two objects will be placed in the same bucket in a hashtable. Your implementation (as I understand it) doesn't match this criteria as the base GetHashCode
implementation is almost certainly going to return different values for two Car
instances, regardless of if they have the same ID or not.
Implementing Equals
and GetHashCode
isn't entirely trivial and is probably something I'd generally avoid doing if there are alternatives. If you really want to do this then take a look at these resoruces:
Also hash codes are not GUIDs