-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pattern matching: completeness vs bool and enum types #11438
Comments
They should, definitely, not be errors! And I can always |
@paulomorgado Sure, but the more interesting question is what happens if we require |
I think so, but only as a part of #1580.
Which is still
This one is tougher. Given that nothing in C# nor the runtime can prevent someone from explicitly casting some garbage value to an enum I want to say that you can't technically consider the match complete without a default/wildcard case. But it should be an exceptional case. Personally I think that there should be no warning for an extraneous |
Right now, this is en error ("CS0161 'IsA(Foo)': not all code paths return a value"): enum Foo
{
A, B
}
bool IsA(Foo foo)
{
switch(foo)
{
case Foo.A:
return true;
case Foo.B:
return false;
}
} I think a sensible way to make that code compile is to add bool IsA(Foo foo)
{
switch(foo)
{
case Foo.A:
return true;
case Foo.B:
return false;
default:
throw new Exception();
}
} But now that would be a warning? Unless the first sample above worked in C# 7, I think adding the warning for I would like to have "strong" enums, which can't have values that are not named. But the reality is that |
I personally think, that a warning should be issued for the |
Strange enough, the C# 5.0 Language Spec (4.1.8) states that "The possible values of type |
@gafter, as @HaloFour mentioned, in practice, Booleans are only true or false. Having a default won't change the meaning of the program. But there's something wrong if the developer adds a As for enums (flags or not) they can assume any value of its base type. So, a match expression needs a |
We resolved to handle this as follows:
This is currently implemented in master. |
In the future, I will be using the term exhaustive/exhaustiveness instead of complete/completeness for this aspect of pattern-matching. |
If a
switch
statement handles cases fortrue
andfalse
, should there be a warning that adefault
case's body isn't reachable?Similar questions for (non-flags) enum types (when there are cases for all the named members).
For backward compatibility, we probably cannot add such new warnings. Also, it is actually possible to get values outside these named examples (e.g., one can construct a bool that contains the value
23
).Perhaps such warnings are deserved in a new expression-based
match
?The text was updated successfully, but these errors were encountered: