You can use it to override the &&
and ||
operators.
The &&
and ||
operators can’t be overridden, but if you override |
, &
, true
and false
in exactly the right way the compiler will call |
and &
when you write ||
and &&
.
For example, look at this code (from http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading – where I found out about this trick; archived version by @BiggsTRC):
public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new AndExpression(lhs, rhs);
}
public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new OrExpression(lhs, rhs);
}
public static bool operator false(AbstractCriterion criteria)
{
return false;
}
public static bool operator true(AbstractCriterion criteria)
{
return false;
}
This is obviously a side effect and not the way it’s intended to be used, but it is useful.