I have the following scenario:
public class SomeClass {
// Have some other data members as well
public int i ;
}
public class TestClass {
public bool SomeFunction() {
SomeClass a = new SomeClass();
SomeClass b = new SomeClass();
if (a == b) // this is where I am getting compile error
return true;
return false;
}
public static bool operator==(SomeClass a, SomeClass b) {
if (a.i == b.i)
return true;
// compare some other members as well
return false;
}
}
Is this possible to achieve in C#?
Thanks for the help!
No, it’s not possible to override an operator from a class that is not involved in the operation.
You can make a class that implements
IEualityComparer<SomeClass>, which can be used instead of the standard comparison in some cases, for example in a dictionary:If you just want to use the comparison in your own class, you could make it a regular static method instead of overriding an operator:
Usage: