2

Given the class as follows,

public class Number
{
  public int X { get; set; }
  public int Y { get; set; }
}

How to define an overload operator == so that I can use the following statement:

Number n1 = new Number { X = 10, Y = 10 };
Number n2 = new Number { X = 100, Y = 100 };

if (n1 == n2)
    Console.WriteLine("equal");
else
    Console.WriteLine("not-equal");

// Updated based on comments as follows //

Here is a further question: It seems to me that C# does operator overload differently from that of C++. In C++, this overloaded operator is defined outside of the targeting class as a standalone function. Here in C#, this overload function in fact is embedded into the targeting class.

Can someone give me some comments on this topic?

Thank you

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    public class Number
    {
        public int X { get; set; }
        public int Y { get; set; }

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

        public static bool operator==(Number a, Number b)
        {
            return ((a.X == b.X) && (a.Y == b.Y));
        }

        public static bool operator !=(Number a, Number b)
        {
            return !(a == b);
        }

        public override string ToString()
        {
            return string.Format("X: {0}; Y: {1}", X, Y);
        }

        public override bool Equals(object obj)
        {
            var objectToCompare = obj as Number;
            if ( objectToCompare == null )
                return false;

            return this.ToString() == obj.ToString();
        }

        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }

    }

    class Program
    {
        static void Main(string[] arg)
        {
            Number n1 = new Number { X = 10, Y = 10 };
            Number n2 = new Number { X = 10, Y = 10 };

            if (n1 == n2)
                Console.WriteLine("equal");
            else
                Console.WriteLine("not-equal");

            Console.ReadLine();
        }
    }
}
q0987
  • 34,938
  • 69
  • 242
  • 387
  • @Damien, I know how to do this in C++ b/c this overloaded function doesn't have to be inside a class. However, as far as I know, all functions defined in C# has to belong to a class. Then, I found some class defines Equals member function. Here, I just need a simple ==. – q0987 May 11 '11 at 15:05

4 Answers4

11
public static bool operator ==(YourClassType a, YourClassType b)
{
    // do the comparison
}

More information here. In short:

  • Any type that overloads operator == should also overload operator !=
  • Any type that overloads operator == should also should override Equals
  • It is recommended that any class that overrides Equals also override GetHashCode
dtb
  • 213,145
  • 36
  • 401
  • 431
Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
  • Be aware that you should have a look at the `!=` operation, the `Equals` and the `GetHashCode` methods and see if you should implement them differently too. – Emond May 11 '11 at 14:57
  • I am able to write such a function myself b/c it is similar as what we do in C++. Here, I am concern where I should put this function? Inside a class? – q0987 May 11 '11 at 15:06
  • And keep in mind that you should do null checks inside the operator==() using object.ReferenceEquals(left, null) instead of == in order to avoid infinite loops! (The same applies for the right object of course) – eFloh May 11 '11 at 15:13
  • Put it in the class that needs the operator. So if you are overriding the YourClassType class, that is the class that should override the == and != operators and Equals() method. And probably GetHashCode(). – Katie Kilian May 11 '11 at 16:08
1

From the MSDN Docs:

public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return a.x == b.x && a.y == b.y && a.z == b.z;
}

public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
    return !(a == b);
}
Eric Falsken
  • 4,796
  • 3
  • 28
  • 46
  • why should we do this "(object)a == null" rather than "a == null"? – q0987 May 11 '11 at 15:32
  • so that it does not become recursive. If you use if a==b then it will use itself to test. If you use (object)a == (object)b, then the test uses the == implementation from System.Object. – Eric Falsken May 14 '11 at 09:02
1

Here is a short example of how to do it, but I very strongly recommend reading Guidelines for Overloading Equals() and Operator == (C# Programming Guide) to understand the interaction between Equals() and == and so on.

public class Number
{
  public int X { get; set; }
  public int Y { get; set; }

  public static bool operator ==(Number  a, Number b)
  {
    // TODO
  }
}
Ivan Zlatev
  • 13,016
  • 9
  • 41
  • 50
0

overload the operator yourself:

public static bool operator ==(Number a, Number b)
{
    // do stuff
    return true/false;
}
Constantinius
  • 34,183
  • 8
  • 77
  • 85