Reputation: 11439
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?
Upvotes: 14
Views: 6849
Reputation: 144136
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 asT.false(x) ? x : T.&(x, y)
[...]
x
is first evaluated and operatorfalse
is invoked on the result to determine ifx
is definitely false. Then, ifx
is definitely false, the result of the operation is the value previously computed forx
.
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.
Upvotes: 16
Reputation: 18569
From this:
&&, || : The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.
So you can't override that, but you can override &
or |
.
Upvotes: 4
Reputation: 203820
See the MSDN page on which operators can be overloaded:
The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.
That refers to the &&
and ||
operators.
So, in short, override &
and you'll get &&
for free along with it.
Upvotes: 7
Reputation: 149020
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.
Upvotes: 18