Operator case syntax defines data type

Today at work I did a code review, as I do now, but today I saw syntax that I had not seen before. I searched the Internet for this to no avail, and what is even more interesting is that, despite using the same version of Visual Studio, i.e. 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 looks like they checked the type and value at a time. But, as I said, I can’t find it on the Internet, and I get a syntax error at home. I know that C # 7 has a lot of new things, especially in terms of syntactic sugar. Can you explain this?

+4
source share
1 answer

This is a new feature in C # 7 : a matching pattern matching operator that matches types.

What this code does is giving the first branch:

  • It checks to see if there is someObject, prints, or implements a type TypeOne.
  • If yes, then press to someObjectenter the TypeOnevalue to which is assigned valueOne.
  • Then it enters the case block, where you can use it directly valueOne.
+13
source

Source: https://habr.com/ru/post/1675917/


All Articles