Liam
Liam

Reputation: 1199

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?

Upvotes: 8

Views: 10206

Answers (1)

David Arno
David Arno

Reputation: 43264

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.

Upvotes: 17

Related Questions