A more common method than simple xor hash codes, as stated in Philippe's answer, is to use a more complex formula to combine them. Multiply the hash codes of individual fields by different numbers, for example:
public override int GetHashCode() { unchecked { return (firstName.GetHashCode() * 33 ^ lastName.GetHashCode()) * 33 ^ phone.GetHashCode(); } }
(Note that the keyword is unchecked : integer overflow is expected here, and silence is precisely defined behavior.)
This will probably not affect the specific types you are dealing with, but overall it is better. Consider a simple type containing only two integer values. Consider also that the implementation of int GetHashCode() simply returns its own value. If you use simple xor to combine values, you will have many hash collisions for normal code: the simplest example is that each pair of two identical values โโwill generate the same hash code of zero.
The calculation here is actually the calculation performed by Tuple<T1, T2, T3> . I did not write it the way Microsoft did, but the actual calculations and numbers should be the same.
source share