"not-or" pattern simplification without warning #4219
Unanswered
pinkfloydx33
asked this question in
Q&A
Replies: 1 comment
-
As for the warning, the compiler can and should flag unreachable patterns, as it is the case when you break that in a switch statement. public void M(string s) {
switch (s) {
case not null:
case "": // error; can never match
break;
}
} Even if this is by-design, I think we should try to warn in those cases as part of a warning wave. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I ran into a little "quirk" of the
not
pattern while writing out what my brain originally told me was the equivalent of!string.IsNullOrEmpty
:This took me a little bit to track down; I had to look at the compiled IL to see what was happening. This gets translated to a simple
null
check. If you read it (correctly) ass is not null or s is ""
this makes sense since!a || b
simplifies to!a
.The correct way to write this would be to either add parentheses or change
or
toand not
:Once I tracked this down, I had an ah-ha moment. I'm not arguing the semantics of this as it does make sense to me now. However, I'm surprised that the compiler doesn't warn about the essentially dead code (nor did the IDE, though a different issue).
Assuming that the semantics are in fact correct, is it intentional we don't recieve some sort of warning here? (Is that even possible?) I don't think it would be uncommon for someone to read the first example "naturally" the way I did. This took me a little while to figure about and I wouldn't expect most developers to decompile the code if they hit this scenario.
SharpLab
It's incredibly difficult to search for terms like
not
andor
so apologies if this has been discussed before. I also had trouble coming up with a title for this discussion, suggestions welcome.Beta Was this translation helpful? Give feedback.
All reactions