4

Today at work I we did a code review as we do now and again, but today I saw a syntax I haven't seen before. I have searched the web for it to no avail, and what is even more interesting is that, despite using the same version of Visual Studio, that is, 2017 Enterprise, I get a syntax error at home when I try to recreate what I saw at work today. It looked something like this:

switch (someObject) {
    case TypeOne valueOne: action1(); break;
    case TypeTwo valueTwo: action2(); break;
    // ... and so on
}

In other words, it looked like they checked both type and value in one go. But like I said, I can't find it on the internet and I get a syntax error at home. I know there's a lot of new stuff in C# 7, especially in terms of syntactic sugar. Can you explain this?

svick
  • 236,525
  • 50
  • 385
  • 514
Thomas
  • 73
  • 3
  • 3
    Check "Switch statements with patterns" in https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/ – KMoussa Apr 28 '17 at 14:19
  • 3
    It is a new feature of C# 7 called pattern matching [MSDN](https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/) search for `Pattern Matching` – Matthiee Apr 28 '17 at 14:19
  • 4
    Make sure you set your compiler to use C# 7 http://stackoverflow.com/questions/43681882/expression-bodied-get-set-accessors – juharr Apr 28 '17 at 14:27

1 Answers1

13

This is a new C# 7 feature: pattern matching switch statement which matches on types.

What this code does, giving the first branch:

  • It checks if someObject is, derives from or implements type TypeOne.
  • If so, it casts someObject to type TypeOne which is assigned to valueOne.
  • Then it enters the case block where you can directly use valueOne.
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325