This project is read-only.

Allow 'bool?' in condition expressions


To play more nicely with conditional access operator ?., ordinary condition expression (in if statement, conditional expression ?., loops conditions) should be lifted to accept values of type bool?. This allows to write more straightforward code like:
if (node?.IsValid)
Instead of ugly workarounds like:
if (node?.IsValid == true)
if (node?.IsValid ?? false)
if (node?.IsValid.GetValueOrDefault())
This reduces the gap between condition expressions and switch statement that allows values of nullable type since C# 2.0:
bool? flag = ...;
switch (flag) {
  case true: // ...
  case false: // ...
  case null: // ...
This also aligns C# with VB.NET, that supports Boolean? in if statements, conditional expressions, loop conditions and so on:
public sub M(flag as Boolean?)
  if flag then ' emits flag.GetValueOrDefault()
     WriteLine("false or null")
  end if
  dim conditionalExpression = if(flag, "true", "false or null")

  while flag
    // ...
  end while

    // ...
  loop while flag
end sub


madst wrote Jul 17, 2014 at 9:52 PM

I like the idea of this feature, but I think it is too dangerous to allow nullable bools as Boolean expressions in conditionals.

What would be the difference between these two if statements?
if (x?.IsDone) WriteLine("Done!");
else WriteLine("Still working...");

if (!x?.IsDone) WriteLine("Still working...");
else WriteLine("Done!");
It looks like we're simply flipping the condition and swapping the statements. However, with nullables that's no longer the case. What if x is null? Then x?.IsDone is also null. But so is !x?.IsDone! So the former would print Still working... whereas the latter would print Done!.

That's too subtle for the language feature to feel like a good one to add. The behavior of nullable booleans in C# actually makes them not very good booleans!

Do you folks agree?

BlueCode wrote Nov 23, 2014 at 8:28 AM