When to use a GUID for a class
-
11-06-2021 - |
Question
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.
Solution
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:
- What is the best algorithm for an overridden System.Object.GetHashCode?
- Default implementation for Object.GetHashCode().
- implementing the Equals method
Also hash codes are not GUIDs
OTHER TIPS
There wouldn't be any need for it without the reasons I explained above.
If your class doesn't logically have an ID, then it certainly seems odd to include it just for the sake of equality.
For example, if you have two instances which have equal properties for everything apart from ID, are they really non-equal? If they are, you should potentially just use the default implementation of Equals
/GetHashCode
which uses reference identity for equality. Where you would use two objects with the same ID, you just use two references to the same object instead.
It really all depends on the context, and you haven't given much of that - but adding an ID just for equality is a bit of a design smell.