Why overload true and false instead of defining bool operator?

二次信任 提交于 2019-12-02 19:22:09

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.

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.

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));

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!