2

This code is simple, just a normal switch:

bool? isSomething = strSomething switch
{
    "I" => true,
    "D" => false,
    _   => null,
};

However, the compiler gives me the following error:

CS0037 Cannot convert null to 'bool' because it is a non-nullable value type

The variable is clearly a nullable bool bool?, why can't c# compiler figure this out without me having to cast the null to get it to work:

_   => (bool?)null,

Am I not getting this right? isn't the cast unnecessary?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Nean Der Thal
  • 3,189
  • 3
  • 22
  • 40
  • Because expressions in general aren't target-typed. `condition ? 1 : null` fails as well. It's not a trivial matter either, what if the expression was embedded in a larger expression? What would be the correct type then? – Panagiotis Kanavos Sep 09 '19 at 08:43

1 Answers1

3

There is an opened issue #2387 for this in c# lang. Which could be fixed in this candidate for c# 9.

Renat
  • 7,718
  • 2
  • 20
  • 34