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); } }
No, basically.
==uses static analysis, so will use the object==. It sounds like you need to useobject.Equals(x,y)instead (orx.Equals(y)if you know that neither is null), which uses polymorphism.