Reputation: 2139
I have already read tons of articles on properly implementing Equals()
and GetHashCode()
. I have some classes with lots of member variables for which I had to implement an Equals()
method. So far, so good. However, when coming to implementing GetHashCode()
I always get stuck finding a good implementation. As I know for certain classes that they will never be used in a dictionary or hash table, I didn't want to invest time in writing a good GetHashCode()
implementation so I came up with the following dummy "default" implementation:
public override int GetHashCode()
{
Debug.Fail( "If you see this message, implement GetHashCode() properly" );
// Always return the same value for all instances of this class. This ensures
// that two instances which are equal (in terms of their Equals() method)
// have the same hash code.
return 0;
}
I wanted to ask for your opinions if this is a feasible approach.
On one hand, I don't want to spend time on implementing GetHashCode()
when I don't have to. On the other hand, I want my code to be clean and valid. The above implementation ensures that two instances which have the same Equals()
result also have the same hash code. Of course if it really would be used as a key in a dictionary, the performance would be bad. But for this case you would get the debug assertion.
Are there any drawbacks in the above approach which I might have missed?
Upvotes: 2
Views: 154
Reputation: 1499770
If you really don't want to implement it, I would recommend throwing an exception instead (e.g. NotImplementedException
) - then you're not just relying on Debug.Fail
working. If you end up in this situation in a production environment, then failing quickly may well be the best option.
But to be honest, once you've implemented equality it's usually really easy to write GetHashCode
(with code like this, perhaps) - and if it's not easy then that's often a sign that your Equals
method will violate its contract anyway.
Note that GetHashCode
isn't just used for dictionaries - if you try to join two lists in LINQ based on a key of your type, that will use GetHashCode
too. Basically, not implementing it violates the principle of least astonishment. Unless you're the only person using your code (and you have a perfect memory or are willing to check each time you use the type), you should implement it properly, IMO.
Upvotes: 4