About
In this code snippet, we will take a look at pattern matching in C#.
Pattern matching is simply testing if an expression matches certain criteria. For example, Regex often times gets used for more complex pattern matching of strings.
But if we want to pattern match an object we can use the is, and, or and when operators within a switch or if statement. Here I already covered the is operator.
Let’s have a look at the code below to see how to do pattern matching.
Code:
MyClass myClass = new MyClass(); //////////////////////////////////////////////////////////////////////////////////////////////// //Using pattern matching with the if statement. if (myClass is MyClass { MyProperty: > 5 }) Console.WriteLine("MyProperty is bigger than 5."); //Multiple conditions. if (myClass is MyClass m && m.MyProperty > 5 && m.MyProperty < 15) Console.WriteLine("MyProperty is bigger than 5 and smaller than 15."); //or ... if (myClass is MyClass { MyProperty: > 5 and < 15 or < -5 and > -15 }) Console.WriteLine("MyProperty is bigger than |5| smaller than |15|."); //////////////////////////////////////////////////////////////////////////////////////////////// //Using pattern matching with the switch statement. switch (myClass) { case MyClass myCls when myCls.MyProperty == 1: ;//Do something... break; case MyClass myCls when myCls.MyProperty == 2: ;//Do something else ... break; default: break; } //And finally you can use all of the above with the new switch syntax like so: string checkValue(int value) => value switch { <= 10 and > 0 => "Value is between 10 and 0.", < 20 and > 10 => "Value is between 20 and 11.", //... _ => "Value out of range.", }; ; string text = checkValue(5); Console.WriteLine(text); //////////////////////////////////////////////////////////////////////////////////////////////// class MyClass { public int MyProperty { get; set; } = 10; public int MySecondProperty { get; set; } = 15; } ////////////////////////////////////////////////////////////////////////////////////////////////