No, you cannot omit the type (or the var keyword, masking the type), since it is part of the template matching here.
Consider a class hierarchy (this will not compile in C#7 , but will compile in future versions after full implementation)
class Geometry(); class Triangle(int Width, int Height, int Base) : Geometry; class Rectangle(int Width, int Height) : Geometry; class Square(int width) : Geometry;
Now we get the following variable:
Geometry g = new Square(5);
Now we do a switch on it:
using static System.Console; switch (g) { // check that g is a Triangle and deconstruct it into local variables case Triangle(int Width, int Height, int Base): WriteLine($"{Width} {Height} {Base}"); break; // same for Rectangle case Rectangle(int Width, int Height): WriteLine($"{Width} {Height}"); break; // same for Square case Square(int Width): WriteLine($"{Width}"); break; // no luck default: WriteLine("<other>"); break; }
Get back to your business, consider the code:
switch (s) { case string x when x.Length == 3 && int.TryParse(x, out int i): Console.WriteLine($"s is a string that parses to {i}"); break;
So, type checking is part of the pattern matching , and you cannot omit it (and for C#7 it is only available for including types, full support is planned for C#8 ). An example is given from here . The previous step was the when clause for exception handling in C#6
VMAtm
source share