Search code examples
switch-statementc#-8.0switch-expression

c# 8 switch expression not "smart" enough


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?


Solution

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