C # 7 pattern matching for 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; } 

Unfortunately, this seems to be impossible. Is this right or am I doing something wrong?

+3
source share
1 answer

This is possible with C # 7 using when guard:

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

What your version of code does is often called active. For example, defining an extension method:

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

Then your switch can become:

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

If you want to see this feature in a future version of C #, please move this sentence .

+6
source

All Articles