Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Overloading operator ==

Tags:

c#

//overloading operator ==
class Point
{
    private int m_X,int m_Y;

    public static operator == (Point p1 ,Point p2)
    {
        if(object.ReferenceEquals(p1,p2)
            return true;

        if((object)(p1) == null) || ((object)(p2) ==null)
            return false;

        return( (p1.x == p2.x) && (p1.x == p2.x));
    }

    //overloading the != operator
}
  1. Is it necessary to override the Equals function
  2. if the p1 and p2 is not typecasted to object , stack overflow exception is thrown Why we need to the Point objects to typecast to object.
like image 891
Unknown Avatar asked May 09 '26 22:05

Unknown


1 Answers

  1. It is generally a good idea to override the Equals() method if you overload the == operator, because they should return the same result, and Object.Equals() will defer to ReferenceEquals() if you do not override it so the operator and method will have different outcomes. The easy way to do that is to have the operator call the Equals() method (which should have similar code as you have here)

  2. You must cast to Object to perform the == null comparisons, because you're in the overloaded == method, and so without a cast to a base type your operator method is calling itself endlessly to try to evaluate whether p1 == null.

like image 135
KeithS Avatar answered May 11 '26 12:05

KeithS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!