0Pricing
C# Academy · Lesson

Overloading Comparison Operators

Implement ==, !=, and ordering operators.

Comparison Operators and Equality

When you overload == you must also overload !=, and you should override Equals and GetHashCode to keep all forms of equality consistent. C# enforces the operator pairing at compile time.

Overloading == and !=

The compiler requires == and != to be defined together. Each returns a bool describing whether the operands are considered equal.

using System;

public struct Point
{
    public int X, Y;
    public Point(int x, int y) { X = x; Y = y; }

    public static bool operator ==(Point a, Point b) => a.X == b.X && a.Y == b.Y;
    public static bool operator !=(Point a, Point b) => !(a == b);

    public override bool Equals(object obj) => obj is Point p && this == p;
    public override int GetHashCode() => HashCode.Combine(X, Y);
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Point(1, 2) == new Point(1, 2));
        Console.WriteLine(new Point(1, 2) != new Point(3, 4));
    }
}

All lessons in this course

  1. Overloading Arithmetic Operators
  2. Overloading Comparison Operators
  3. User-Defined Conversions
  4. Operator Overloading Best Practices
← Back to C# Academy