Promote "when" from pattern guard to guard pattern #4836
Replies: 3 comments 3 replies
-
I like it :-) |
Beta Was this translation helpful? Give feedback.
-
This means there was something that couldn't be expressed with patterns themselves. Also with a when clause you would lose subsumtion checking and optimal codegen in a switch. I'd suggest user-defined patterns for things like this. #4131 if (obj is Datum { Value: ParseInt(int value) } ) {
// use value here
} |
Beta Was this translation helpful? Give feedback.
-
From my experience (which of course may not be typical), there are
// 2. Matching on types
result = typeof(T1) switch {
T2 => // can't do this
t when t == typeof(T2) => // have to do it this way
// 3. Needing to invoke a method as part of the pattern test
result = x switch {
Datum { Value: var s } when int.TryParse(s, out var value) => do something with value ...
In the last case, as @alrz says, we could neatly solve these by supporting active patterns (which is a glaring hole in C#'s pattern matching features). How it's done is implementation details, but could indeed end up as something like @alrz suggests where any method fitting the pattern result = x switch {
Datum { Value: Parse(var value) } => do something with value ... For the middle case, either pattern matching on types could be directly supported or an active pattern could be used here too. So whilst I like the look of guard patterns, it makes sense to me to |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Currently the
when
keyword is used only inswitch
statements/expressions to allow a boolean expression to be evaluated after a pattern has been matched:This was fine with simple patterns, but with support for more complicated recursive patterns this suffers from the problem that the condition that is to be evaluated can be somewhat distant from the part of the pattern that is relevant for extracting that data.
I propose that the
when
keyword be promoted to a form of pattern itself, a "guard pattern", that can be applied as a conjunctive pattern that applies an arbitrary boolean expression against the partially matched pattern and pattern variables. This would allow the conditions to be embedded within the recursive patterns.The existing uses of
when
as a pattern guard should automatically fall out as a legal pattern.Open Questions:
Beta Was this translation helpful? Give feedback.
All reactions