The output of the following code is as follows:
not equal
Note the difference in type x and xx and that == operator overloading is performed only in the second case, and not in the first.
Is there a way to overload the == operator so that it always runs when comparing between instances of MyDataObejct.
Edit 1: # here I want to redefine the == operator on MyDataClass, I'm not sure how to do this, so that case1 also runs the overloaded implementation ==.
class Program {
static void Main(string[] args) {
Object x = new MyDataClass();
Object y = new MyDataClass();
if ( x == y ) {
Console.WriteLine("equal");
} else {
Console.WriteLine("not equal");
}
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);
}
}
source
share