sircodesalot
sircodesalot

Reputation: 11439

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?

Upvotes: 14

Views: 6849

Answers (4)

Lee
Lee

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 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.

Upvotes: 16

Iswanto San
Iswanto San

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

Servy
Servy

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

p.s.w.g
p.s.w.g

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

Related Questions