Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching on a string

I was wondering if there is a way to do something like this in c# 7

        var test = "aaeag";
        switch (test)
        {
            case test.StartsWith("a"):
                break;
            default:
                break;
        }

Sadly it does not look like it possible. Is this correct or am I doing something wrong?

like image 520
Liam Avatar asked Mar 22 '17 13:03

Liam


1 Answers

This is possible with C# 7, using a when guard:

var test = "aaeag";
switch (test)
{
    case var s when s.StartsWith("a"):
        break;
    default:
        break;
}

What your version of the code is doing is often referred to as active patterns. By eg defining the the extension method:

public static bool StartsWithPattern(this string str, string matchPattern) => 
    str.StartsWith(matchPattern);

Then your switch could become:

var test = "aaeag";
switch (test)
{
    case StartsWith("a"):
        break;
    default:
        break;
}

If you'd like to see this feature in a future C# version, then please upvote this proposal.

like image 177
David Arno Avatar answered Nov 19 '22 13:11

David Arno