Simplify Overriding Equals(), GetHashCode() in C# for Better Maintainability

心不动则不痛 提交于 2019-11-28 12:07:49
Eric J.

MSDN actually doesn't say "don't overload Equals et al for mutable types". It used to say that, but now it says:

When you define a class or struct, you decide whether it makes sense to create a custom definition of value equality (or equivalence) for the type. Typically, you implement value equality when objects of the type are expected to be added to a collection of some sort, or when their primary purpose is to store a set of fields or properties.

http://msdn.microsoft.com/en-us/library/dd183755.aspx

Still, there are complexities surrounding stability of the hash code while an object participates in a hashed collection (Dictionary<T,U>, HashSet<T>, etc.).

I decided to opt for the best of both worlds, as outlined here:

https://stackoverflow.com/a/9752155/141172

I find my self overriding Equals() and GetHashCode() frequently

  • MSDN says : don't overload Equals et al for mutable types

Is ^ adequate given that the contributing component values are well-distributed?

  • Yes, but hey are not always well distributed. Consider int properties. Shifting with some (small) prime numbers is advised.

Perhaps I'm confused here, but shouldn't the on null check return a 1 instead of a 0 in the GetHashCode override?

So

MyStringProp == null ? 0 : MyStringProp.GetHashValue()

should be

MyStringProp == null ? 1 : MyStringProp.GetHashValue()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!