Search This Blog

Loading...

Wednesday, October 29, 2008

How to Use == Operator Correctly

Overriding == Operator seems to be easy, way to easy to warrant a blog post, right?

Wrong.

To see this, let's define a simple class

public class Point2D
{
   int double X{get;set;}
  int double Y{get;set;}

public override bool Equals(object value)
{
  Point2D pt2D = (Point2D)value;
  return X==pt2D.X && Y== pt2D.Y;
}

}

Now let's just set the == Operator to call Equals

public static bool operator == (Point2D left, Point2D right)
{
   return left.Equals(right);
}
 This works in most circumstances, but this doesn't work if the left is null.

Want to have another try? Let's just check the value for null before we call the left.Equals(right)! And this should solve the problem, right?

public static bool operator == (Point2D left, Point2D right)
{
if (left == null && right == null)
return true;
if (left != null && right == null)
return false;
if (left == null && right != null)
{
return false;
}
   return left.Equals(right);
}

Now, if you try this test

        [Test]
        public void EqualTestNull()
        {
            Point2D pt1 = null;
            Point2D pt2 = null;
            Assert.IsTrue(pt1==pt2);
        }
 You will find that a StackOverflow exception is thrown, this is because the program keeps on looping at the first statement left==null && right == null. This is because whenever you compare using the == operator, the comparison will go into recursive mode, resulting in an infinite recursive calling and hence crash the test.

The solution to solve this problem is to cast the Point2D object to object before you compare it to null:
if ((object)left == null && (object)right == null)
return true;
if ((object)left != null && (object)right == null)
return false;
if ((object)left == null && (object)right != null)
{
return false;
}
return left.Equals(right);

Only then you can fix the problem.

Or alternatively, you need to use a static method Equals(object, object) provided by Microsoft insite the == Operator method:
public static bool operator == (Point2D left, Point2D right)
{
return Equals(left, right);
}

2 comments:

mr_ST said...

object.ReferenceEquals better solution instead of casting

Sandeep said...

Great article

Thanks for the information

http://extreme-java.blogspot.com/2007/12/method-overriding-rules-in-java.html