Argument Deconstruct #6055
Replies: 4 comments 6 replies
-
What should happen if the pattern matching fails? |
Beta Was this translation helpful? Give feedback.
-
I want to say that we've also had a proposal or two about overloading via patterns, where the overload invoked depending on which pattern matches the arguments in lexicographical order. That kind of overloading is more commonly found in functional languages and is resolved at runtime whereas in C# overload resolution occurs at compile time. This proposal appears to be infallible deconstruction via pattern matching, where the signature of the method must refer to the type of each formal parameter and where you can't have multiple methods where those types overlap but the patterns differ. Presumably the pattern would have to be infallible, which might limit their usefulness, although one could argue that a fallible pattern could also serve as an inline form of method contract. void PrintFoo(Foo { Bar: var bar } foo) => Stuff(bar, 0);
// compiles to:
void PrintFoo(Foo foo) {
var bar = foo.Bar;
Stuff(bar, 0);
}
// fallible:
void PrintFoo(Foo { Bar: string bar } foo) => Stuff(bar, 0);
// compiles to:
void PrintFoo(Foo foo) {
if (foo is { Bar: string bar }) {
Stuff(bar, 0);
}
else {
throw new ArgumentException(nameof(foo));
}
} |
Beta Was this translation helpful? Give feedback.
-
If patterns applied to parameters can be used for validation and deconstruction, maybe this could be a general validation mechanism which would also enable simple null checking. void X(string { } str) { } Not that I like that syntax but at least it would be consistent with current |
Beta Was this translation helpful? Give feedback.
-
Mainly thinking in the infallible cases, this could be nice to lambdas too Action<Foo> a = ((bar, baz)) => Stuff(bar, baz);
Action<Foo> a = ({ Bar: var bar, Baz: var baz }) => Stuff(bar, baz);
Action<Foo> a = ({ Bar: var bar }) => Stuff(bar, 0); |
Beta Was this translation helpful? Give feedback.
-
Being able to focus on just a part of a data structure can be very handy sometimes, would be nice to have a way to deconstruct arguments in a similar way we do in pattern matching.
This works today:
This prosal:
Beta Was this translation helpful? Give feedback.
All reactions