Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order matter when overriding the == operator?

Tags:

c#

In C# I can override == with my own implementation. For example:

public static bool operator ==(SomeType x, SomeOtherType y)
{
    return false;
}

Does the order of parameters matter here? Does it make a difference to swap SomeType with SomeOtherType?

like image 781
sdgfsdh Avatar asked Sep 01 '25 10:09

sdgfsdh


1 Answers

Yes it does. In your case,

SomeType x;
SomeOtherType y;
bool b = x == y;

would call your function, but

bool b = y == x;

would not.

Overloaded operator functions in this respect have the same behaviour as any regular function with more than one parameter type: the passed parameters must match the expected types with the order clearly mattering too.

like image 169
Bathsheba Avatar answered Sep 04 '25 02:09

Bathsheba