I've been searching for actual working code where an overloaded false
operator actually gets executed.
This question (What's the false operator in C# good for?) is somewhat the same, but the accepted answer links to an url which is returning a 404 error. I've also looked at How does operator overloading of true and false work? and some other questions.
What I've found in almost all answers is that false
only gets executed when you use a short circuited and like x && y
. This is evaluated as T.false(x) ? x : T.&(x, y)
.
Ok, so I have the following code. The struct
contains an int
and considers itself true if the int is greater than zero.:
public struct MyStruct {
private int _i;
public MyStruct(int i) {
_i = i;
}
public static bool operator true(MyStruct ms) {
return ms._i > 0;
}
public static bool operator false(MyStruct ms) {
return ms._i <= 0;
}
public override string ToString() {
return this._i.ToString();
}
}
Now I would hope the following program will execute and use the overloaded false
operator.
class Program {
private static void Main() {
MyStruct b1 = new MyStruct(1); // to be considered true
MyStruct b2 = new MyStruct(-1); // to be considered false
Console.WriteLine(b1 && b2);
Console.WriteLine(b2 && b1);
}
}
However, it does not even compile. It says it cannot apply operator '&&' to operands of type 'MyStruct' and 'MyStruct'.
I know I can implement an overload of the &
operator. So let's do that. The &
must return a MyStruct
, so I can not make it return a bool
.
public static MyStruct operator &(MyStruct lhs, MyStruct rhs) {
return new MyStruct(lhs._i & rhs._i);
}
Now the code does compile. Its output is 1
and -1
. So the result of b1 && b2
is not the same as that of b2 && b1
.
If I debug the code, I see that b1 && b2
first executes the false
operator on b1
, which returns false
. Then it performs the &
operator on b1 and b2, which performs a bitwise and on 1 and -1, resulting in 1. So it indeed is first checking if b1 is false.
The second expression, b2 && b1
first executes the false
operator on b2
, which returns true
. Combined with the fact I'm using short circuiting, it doesn't do anything with b1
and just prints out the value of b2
.
So yes, the false
operator is executed when you use short circuiting. However, it does not execute the true
or false
operator on the second argument, but instead executes the overloaded &
operator on the operands.
When can this ever be useful? Or how can I make my type so that it can check if the two variables both are true?