Pattern Matching C# with Example
Pattern matching extensions for C# enable many of the benefits of pattern matching from functional languages, but in a way that smoothly integrates with the feel of the underlying language switch expression Pattern matching extends the switch statement to switch on types: class Geometry {} class Triangle : Geometry { public int Width { get; set; } public int Height { get; set; } public int Base { get; set; } } class Rectangle : Geometry { public int Width { get; set; } public int Height { get; set; } } class Square : Geometry { public int Width { get; set; } } public static void PatternMatching() { Geometry g = new Square { Width = 5 }; switch (g) { case Triangle t: Console.WriteLine($"{t.Width} {t.Height} {t.Base}"); break; case Rectangle sq when sq.Width == sq.Height: Console.WriteLine($"Square rectangle: {sq.Width} {sq.Height}"); break; case Rectangle r: Console.WriteLine($"{r.Width} {r.Height}"); break; case Square s: Console.WriteLine($"{s.Width}"); break; default: Console.WriteLine(""); break; } } is expression Pattern matching extends the is operator to check for a type and declare a new variable at the same time. Example Version < 7.0 string s = o as string; if(s != null) { // do something with s } can be rewritten as: Version ≥ 7.0 if(o is string s) { //Do something with s }; Also note that the scope of the pattern variable s is extended to outside the if block reaching the end of the enclosing scope, example: if(someCondition) { if(o is string s) { //Do something with s } else { // s is unassigned here, but accessible } // s is unassigned here, but accessible } // s is not accessible here