C# Pattern Matching

C# Code Snippets Pattern matching
Share:

About

In this code snippetwe 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;
}


////////////////////////////////////////////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger