What's the false operator in C# good for?

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.


Shog9 and Nir: thanks for your answers. Those answers pointed me to Steve Eichert article and it pointed me to msdn:

The operation x && y is evaluated as T.false(x) ? x : T.&(x, y), where T.false(x) is an invocation of the operator false declared in T, and T.&(x, y) is an invocation of the selected operator &. In other words, 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. Otherwise, y is evaluated, and the selected operator & is invoked on the value previously computed for x and the value computed for y to produce the result of the operation.


The page you link to http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx says what they were for, which was a way of handling nullable bools before nullable value types were introduced.

I'd guess nowadays they're good for the same sort of stuff as ArrayList - i.e. absolutely nothing.

Tags:

C#

.Net

Syntax