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

后端 未结 2 1644
小蘑菇
小蘑菇 2020-12-06 09:57

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 instea

相关标签:
2条回答
  • 2020-12-06 10:12

    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.

    0 讨论(0)
  • 2020-12-06 10:30

    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");
    }
    
    0 讨论(0)
提交回复
热议问题