In C#, why do I need to type return when it is heuristically unreachable?

Viewed 81

This simple C# method becomes non compilable when the final return statement is removed. Why? I would say that the switch is complete and thus the final return is unreachable.

private static object Convert(bool? predicate)
{
    switch (predicate)
    {
        case false: return null;
        case true: return null;
        case null: return null;
    }

    return null;
}

EDIT: I'm using C# 7.3 That's probably the reason why.

2 Answers

Because the compiler isn't always perfect, and you're using an older compiler. If you use a C# 8.0 compiler: it works exactly as you want.

Marc is correct regarding this being down to the capability of the compiler. If you're stuck on an earlier version of C# and want to declare your intent a little better you can consider throwing an InvalidOperationException on the case that should never happen;

private static object Convert(bool? predicate)
{
    switch (predicate)
    {
        case false: return null;
        case true: return null;
        case null: return null;                
        default: throw new InvalidOperationException();
    }
}
Related