Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override && (logical and operator)?

Everything else seems to follow this pattern, but when I try:

public static ColumnOperation operator&&(ColumnOperation lhs, ColumnOperation rhs)
{
    return new ColumnBooleanOperation(lhs, rhs, ExpressionType.And);
}

I get "Overloadable binary operator expected". What am I doing wrong?

like image 998
sircodesalot Avatar asked Mar 15 '13 18:03

sircodesalot


2 Answers

Conditional logic operators cannot be overloaded.

According to the documentation:

The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.

This article provides more information on how to implement your own custom && and || operators.

like image 102
p.s.w.g Avatar answered Oct 15 '22 20:10

p.s.w.g


You can't overload && directly, but you can overload the false, true and & operators - see operator &&

public static bool operator true(ColumnOperation x)
{
    ...
}

public static bool operator false(ColumnOperation x)
{
    ...
}

public static ColumnOperation operator &(ColumnOperation lhs, ColumnOperation rhs)
{
    return new ColumnBooleanOperation(lhs, rhs, ExpressionType.And);
}

This gives the same functionality. Specifically, from here:

The operation x && y is evaluated as T.false(x) ? x : T.&(x, y)
[...]
x is first evaluated and operator false is invoked on the result to determine if x is definitely false. Then, if x is definitely false, the result of the operation is the value previously computed for x.

This indicates that short-circuit evaluation will also work as expected when the above overloads are implemented correctly. Overloading the | can also be done in a similar fashion.

like image 35
Lee Avatar answered Oct 15 '22 18:10

Lee