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

前端 未结 5 1550
無奈伤痛
無奈伤痛 2020-11-30 18:21

There are two weird operators in C#:

  • the true operator
  • the false operator

If I understand this right these operators can be used in typ

5条回答
  •  庸人自扰
    2020-11-30 18:47

    It appears from the MSDN article you linked to it was provided to allow for nullable boolean types prior to the Nullable (i.e. int?, bool?, etc.) type being introducted into the language in C#2. Thus you would store an internal value indicating whether the value is true or false or null, i.e. in your example >0 for true, <0 for false and ==0 for null, and then you'd get SQL-style null semantics. You would also have to implement a .IsNull method or property in order that nullity could be checked explicitly.

    Comparing to SQL, imagine a table Table with 3 rows with value Foo set to true, 3 rows with value Foo set to false and 3 rows with value Foo set to null.

    SELECT COUNT(*) FROM Table WHERE Foo = TRUE OR Foo = FALSE
    6
    

    In order to count all rows you'd have to do the following:-

    SELECT COUNT(*) FROM Table WHERE Foo = TRUE OR Foo = FALSE OR Foo IS NULL
    9
    

    This 'IS NULL' syntax would have equivilent code in your class as .IsNull().

    LINQ makes the comparison to C# even clearer:-

    int totalCount = (from s in MyTypeEnumerable
                     where s || !s
                     select s).Count();
    

    Imagining that MyTypeEnumberable has exactly the same contents of the database, i.e. 3 values equal to true, 3 values equal to false and 3 values equal to null. In this case totalCount would evaluate to 6 in this case. However, if we re-wrote the code as:-

    int totalCount = (from s in MyTypeEnumerable
                     where s || !s || s.IsNull()
                     select s).Count();
    

    Then totalCount would evaluate to 9.

    The DBNull example given in the linked MSDN article on the false operator demonstrates a class in the BCL which has this exact behaviour.

    In effect the conclusion is you shouldn't use this unless you're completely sure you want this type of behaviour, it's better to just use the far simpler nullable syntax!!

    Update: I just noticed you need to manually override the logic operators !, || and && to make this work properly. I believe the false operator feeds into these logical operators, i.e. indicating truth, falsity or 'otherwise'. As noted in another comment !x won't work off the bat; you have to overload !. Weirdness!

提交回复
热议问题