C # 7 body with zero checks

C # 7 introduces a new feature called templates, which you can use with Is-Expression or Switch examples, for example:

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

and you expect it to go into register # 1, since it is the same type, but it did not.

+7
c # pattern-matching switch-statement
Mar 22 '17 at 11:51 on
source share
2 answers

Despite what you think, string x = null actually nothing. This "nothing" is assigned to a variable of type string.

Testing your switch is basically the same as null is string , which has been false for a long time. This is a common problem when evaluating types using generics, but it also has its plus points.

Under the hood is used as zero-checked. Therefore, he cannot return the truth. You could say that the logic for the is operator is as follows:

 is = (null as string) != null 
+14
Mar 22 '17 at 11:53 on
source share

this is actually not due to the null string.

The idea is that switch cases with templates in C # 7 add another case to check for Null when evaluating cases, and if you haven't added your Null case check, it will go to the default case, so better add a null case when using this new feature or leave it as default if you know what the default is doing.

Hope this helps!

0
Mar 22 '17 at 11:51 on
source share



All Articles