Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

== operator overloading when object is boxed

Tags:

c#

The output of the below code is as following:

not equal
equal

Note the difference in type of x and xx and that == operator overload is only executed in the second case and not in the first.

Is there a way I can overload the == operator so that its always executed when a comparison is done on between MyDataObejct instances.

Edit 1:# here i want to override the == operator on MyDataClass , I am not sure how I can do it so that case1 also executes overloaded == implementation.

class Program {
    static void Main(string[] args) {
        // CASE 1
        Object x = new MyDataClass();
        Object y = new MyDataClass();
        if ( x == y ) {
            Console.WriteLine("equal");
        } else {
            Console.WriteLine("not equal");
        }

        // CASE 2 
        MyDataClass xx = new MyDataClass();
        MyDataClass yy = new MyDataClass();
        if (xx == yy) {
            Console.WriteLine("equal");
        } else {
            Console.WriteLine("not equal");
        }
    }
}

public class MyDataClass {
    private int x = 5;

    public static bool operator ==(MyDataClass a, MyDataClass b) {
        return a.x == b.x;
    }

    public static bool operator !=(MyDataClass a, MyDataClass b) {
        return !(a == b);
    }
}
like image 338
dotnetcoder Avatar asked Apr 09 '09 11:04

dotnetcoder


1 Answers

No, basically. == uses static analysis, so will use the object ==. It sounds like you need to use object.Equals(x,y) instead (or x.Equals(y) if you know that neither is null), which uses polymorphism.

like image 186
Marc Gravell Avatar answered Sep 27 '22 17:09

Marc Gravell