Please navigate to the bottom of the page for Table of Contents

Friday, May 27, 2011

Operator overloading and pairing rules in C#

What is the problem in the following code snippet?

namespace ConsoleApplication1
struct Point
int X;
int Y;

public static bool operator ==(Point p1, Point p2)
return ((p1.X == p2.X) && (p1.Y == p2.Y));

When you overload equality (==, !=) and comparison (<, >, <=, >=) operators, special pairing and overriding rules are enforced by C# compiler. For the above example, the compiler generates 2 warnings and the 1 error:

  • Warning: 'ConsoleApplication1.Point' defines operator == or operator != but does not override Object.GetHashCode()

  • Warning: 'ConsoleApplication1.Point' defines operator == or operator != but does not override Object.Equals(object o)

  • Error: The operator 'ConsoleApplication1.Point.operator ==(ConsoleApplication1.Point, ConsoleApplication1.Point)' requires a matching operator '!=' to also be defined   

Rule 1: If you overload the equality operators (== and !=), it is good practice to override the GetHashCode() and Equals() methods. Reason: Collections and HashTables rely on equality relations to work reliably.

Rule 2: If you overload one operation that is part of a pair (for example, == and !=), you are required to implement the other operator.

Rule 3: If you overload the comparison operators (< and >), it is a good practice to implement IComparable and IComparable<T> for the same reasons defined for rule 1.