I\'ve been reading about overloading true and false in C#, and I think I understand the basic difference between this and defining a bool operator. The example I see around is
I had no idea these operators existed. That means you can implement the self-negation paradox:
public class ThisClassIsFalse
{
public static bool operator true(ThisClassIsFalse statement)
{
return statement ? false : true;
}
public static bool operator false(ThisClassIsFalse statement)
{
return statement ? true : false;
}
}
So now we know the true solution to this classic paradox... StackOverflowException.
As the docs say, overloading true
and false
is intended to support (nullable) database-types (Yes/No, Y/N, 0/1, etc).
And of course you can define them inconsistently, as with any operator. It is your responsibility to return something sensible. The compiler goes no further than requiring neither or both.
Depending on the system, true can be any non-zero value. In others, it can be any positive value.
Other systems aren't truly boolean, and allow a third state null or nill for the boolean values, which is why you might overload true and false, versus overloading a single bool operator.
I've seen people overload the true
and false
overloads in order to do clever things like building expressions in .NET 2.0, before Linq existed.
Ayende worked out a syntax like this to build NHibernate criteria queries, using his NHQG project:
return Repository.FindAll(
(Where.Publisher.Name == name) &&
(Where.Publisher.City == city));