Framework Fundamentals(Chapter 6 of C# 4.0 in a nutshell)
Here are the other rules for overriding object.GetHashCode:
• It must return the same value on two objects for which Equals returns true(hence, GetHashCode and Equals are overridden together).
• It must not throw exceptions.
• It must return the same value if called repeatedly on the same object (unless the object has changed).
Code
1 public struct Area : IEquatable <Area>
2 {
3 public readonly int Measure1;
4 public readonly int Measure2;
5 public Area (int m1, int m2)
6 {
7 Measure1 = Math.Min (m1, m2);
8 Measure2 = Math.Max (m1, m2);
9 }
10 public override bool Equals (object other)
11 {
12 if (!(other is Area)) return false;
13 return Equals ((Area) other); // Calls method below
14 }
15 public bool Equals (Area other) // Implements IEquatable<Area>
16 {
17 return Measure1 == other.Measure1 && Measure2 == other.Measure2;
18 }
19 public override int GetHashCode()
20 {
21 return Measure2 * 31 + Measure1; // 31 = some prime number
22 }
23 public static bool operator == (Area a1, Area a2)
24 {
25 return a1.Equals (a2);
26 }
27 public static bool operator != (Area a1, Area a2)
28 {
29 return !a1.Equals (a2);
30 }
31 }
2 {
3 public readonly int Measure1;
4 public readonly int Measure2;
5 public Area (int m1, int m2)
6 {
7 Measure1 = Math.Min (m1, m2);
8 Measure2 = Math.Max (m1, m2);
9 }
10 public override bool Equals (object other)
11 {
12 if (!(other is Area)) return false;
13 return Equals ((Area) other); // Calls method below
14 }
15 public bool Equals (Area other) // Implements IEquatable<Area>
16 {
17 return Measure1 == other.Measure1 && Measure2 == other.Measure2;
18 }
19 public override int GetHashCode()
20 {
21 return Measure2 * 31 + Measure1; // 31 = some prime number
22 }
23 public static bool operator == (Area a1, Area a2)
24 {
25 return a1.Equals (a2);
26 }
27 public static bool operator != (Area a1, Area a2)
28 {
29 return !a1.Equals (a2);
30 }
31 }