I'm looking at C# 7's new switch statement, and while it's awesome that I can switch on the type as part of pattern matching, I wonder if I can avoid re-stating the type in case I already know it?
Example:
private static void BetterSwitchCase(string s)
{
switch (s)
{
case string x when x.Length == 3 && int.TryParse(x, out int i):
Console.WriteLine($"s is a string that parses to {i}");
break;
default:
Console.WriteLine("No Match.");
break;
}
}
Here, my case statement re-states string x
even though the type I'm switching on is already a string, and I only care about it's Length
and if it int.TryParse
s.
Just omitting it doesn't compile:
// Syntax error, ':' expected
case when s.Length == 3 && int.TryParse(s, out int i):
// A constant value is expected
case s when s.Length == 3 && int.TryParse(s, out int i):
So I'm just wondering if there is a way to omit it, or if it's just part of the pattern matching syntax that I have to accept.
You could use var
pattern:
case var x when x.Length == 3 && int.TryParse(x, out int i):
Or even better, var
pattern with a discard:
case var _ when s.Length == 3 && int.TryParse(s, out int i):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With