Support irrefutable patterns #2988
Replies: 5 comments
-
Well you could do the following in this specific case, which compiles just fine: public static string Example() => ("Hello", "world") switch
{
(string hello, string world) =>
string.Concat(hello, " ", world)
}; |
Beta Was this translation helpful? Give feedback.
-
That doesn't know that the list of cases is exhaustive though, it still emits the fallback code that throws a |
Beta Was this translation helpful? Give feedback.
-
This one doesn't work as well string Example()
{
if ("Hello" is var hello) {
return hello;
}
} @Unknown6656 my case is a bit more specific, I need a statement for one branch: private (string Name, string Value) GetFoo(Order order)
{
switch (order.Name ?? string.Empty, order.Value ?? string.Empty)
{
case ("", ""):
string generatedNameValue = GenerateNameValue()
if (string.IsNullOrEmpty(generatedNameValue ))
{
throw new InvalidOperationException();
}
return (generatedNameValue, generatedNameValue);
case (string name, ""):
return (name, name);
case ("", string value):
return (value, value);
case (string name, string value):
return (name, value);
default:
throw new System.Exception("Unreachable");
}
} I'm yet to see how to rewrite it without ugly exception in the end. The only way I could think is to move block into local function and pattern match on that. Anyway, I think pattern match statement is perfectly valid and should work as described. |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
type pattern also implicates a null check so those are not necessarily irrefutable, only a |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Currently pattern matching in C# doesn't support irrefutable patterns. For example this one should be perfrectly valid
although it currently fails with
CS0161 'Example()': not all code paths return a value
.Others languages with pattern matching know that this pattern would never fail. This is a Rust example:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=47f66c9bedf2439cbba9deb28948a9f6
Beta Was this translation helpful? Give feedback.
All reactions