C# 7 switch case with null checks

淺唱寂寞╮ 提交于 2019-12-08 21:46:01

问题


C#7 introduces a new feature called patterns, which you can use with Is-Expression or Switch cases like this:

string str = null; 
switch(str){
    case string x:
        Console.WriteLine("string " + x);
        break;
    default:
        Console.WriteLine("default");
        break;
}

and you would expect that it will goes inside case #1, as it is the same type, but it didn't.


回答1:


Despite what you might think, string x = null actually isn't a string at all. It is 'nothing', assigned to a variable of type string.

The check in your switch is basically the same as null is string which is false for a long time already. This is a common issue when evaluating types with generics, but it has its plus sides too.

Under the hood, is uses as, with a null check. So that is why it can't return true. You could say the logic for the is operator is as follows:

is = (null as string) != null



回答2:


actually they are not because of the null on string.

the idea is that switch cases with patterns in c#7 adds another case for Null checking while evaluating the cases, and if you didn't add your Null case check, it will go to default case, so it is better to add a null case while using this new feature, or leave it to default if you know what default will do.

Hope it helps!



来源:https://stackoverflow.com/questions/42950833/c-sharp-7-switch-case-with-null-checks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!