Similar questions have been asked, but I'm not sure I understand the answers correctly. I am referring to a situation where the equality operator is overridden in one or both classes. Please explain if I'm right. If I write if(a == b) { ... }
, then equality operator of the class of "a" is used and in case of if(b == a) { ... }
is used then equality operator defined in the class of "b". The equality operator of which class is used if I write if(null == a) { ... }
.
If I understand correctly: C# Equality operator ( == ) and order of operands
132 Views Asked by retrograde.su At
2
There are 2 best solutions below
1

public class Program
{
public static void Main()
{
var foo = new Foo();
if(foo == null)
{
}
if(null == foo)
{
}
}
}
public class Foo
{
public static bool operator ==(Foo a, Foo b)
{
Console.WriteLine("Foo operator == called");
return ReferenceEquals(a, b);
}
public static bool operator !=(Foo a, Foo b)
{
Console.WriteLine("Foo operator != called");
return !(a == b);
}
public override bool Equals(object obj)
{
Console.WriteLine("Foo Equals() called");
return ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
Console.WriteLine("Foo GetHashCode() called");
return base.GetHashCode();
}
}
Output:
Foo operator == called
Foo operator == called
So in both cases the equality operator of class Foo
will be called.
We can do that and test... something like the following?
Then you write code such as:
Then you get:
Does that answer your question? Have a look at the code, when you define the operator
==
you specify the types of the parameters, and the compiler uses that to choose the operator to call. In this case it finds two operators that have operandsA
andB
in that order and that results in an ambiguous call (the compiler does not know - does not have a way to decide - which one to use).That depends on the types of the operands. If you always put the operant of the type of the current class as first, then that is true. For example:
Output:
A
.However, if define the operators with the operands in the opposite order...
Output:
B
.First, let us be clear.
B
or any other classes are irrelevant here. They do not affect the outcome of this comparison, because you are not using them here. It would be very inconvenient if they did.Let us try:
Output: .
We get no output, because the called operator is none of the ones defined here... intead it is using the default operator (the one for
object
).Wait! What if I change the order of operands?
Output:
A
.Now we are using the operator on
A
because it matches the operand types better than the default operator does.