Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I simplify this C# 7 switch statement to not re-state the type?

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.TryParses.

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.

like image 302
Michael Stum Avatar asked Apr 13 '17 21:04

Michael Stum


1 Answers

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):
like image 63
svick Avatar answered Sep 30 '22 12:09

svick