Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on Nullable Boolean : case goes to null when value is true

Tags:

I realize the proper way to handle nullable types is to use the HasValue property. But I would like to know why the following switch statement breaks on the null case instead of default. Using VS2015 C#4.0. Another computer that is using VS2010 C#4.0 does not have this same problem.

 private void Testing()
    {
        bool? boolValue = true;

        switch (boolValue)
        {
            case null: 
                break; //even though value is true, code runs here

            default:
                break;
        }
    }

Edit: Behavior is observed with any Nullable if only case Null and default is specified.

like image 943
MikeG Avatar asked Sep 04 '15 22:09

MikeG


2 Answers

This is going to be a very short answer: You just hit Roslyn bug #4701, reported two weeks ago.

The milestone is set to 1.1, so right now you'll have to workaround this with a separate if clause, while waiting for the next compiler update.

like image 199
Lucas Trzesniewski Avatar answered Nov 30 '22 22:11

Lucas Trzesniewski


This is not an answer, I am just sharing IL code generated by VS2013 and VS2015.

Original C# code:

public void Testing()
{
    bool? boolValue = true;

    switch (boolValue)
    {

        case null:

            Console.WriteLine("null");

            break; 

        default:
            Console.WriteLine("default");

            break;
    }
}

VS2013 IL (decompiled):

public void Testing()
{
    bool? boolValue = new bool?(true);
    bool valueOrDefault = boolValue.GetValueOrDefault();
    if (boolValue.HasValue)
    {
        Console.WriteLine("default");
    }
    else
    {
        Console.WriteLine("null");
    }
}

VS2015 IL (decompiled):

public void Testing()
{
    bool? flag = new bool?(true);
    bool? flag2 = flag;
    bool? flag3 = flag2;
    if (flag3.HasValue)
    {
        bool valueOrDefault = flag3.GetValueOrDefault();
    }
    Console.WriteLine("null");
}
like image 43
Yacoub Massad Avatar answered Dec 01 '22 00:12

Yacoub Massad