c sharp

C# Pattern Matching With is and switch

Pattern matching is a process that is highly used in computing. It tests and matches the particular patterns in expressions. Pattern matching is highly used in a variety of ways to check and test the expression such as, to identify the constant value of the expression according to the specified type. This article will analyze pattern matching in C# and also provide various methods with program examples to demonstrate pattern matching.

What is Pattern Matching in C#?

At first pattern matching concept is introduced in C# 7.0, later versions of C# make more improvements in its functionality. Pattern Matching is a technique of comparing expressions according to the specified structures or patterns to see if there is any match or not. It provides conditional logic simpler and makes it possible to extract useful details from the structures of data(such as an expression) or an object.

Operations of Pattern Matching

Pattern matching provides us with many operations such as, “is”, and “switch” expressions, constant patterns, relational, and many more patterns. Now, we implement examples of pattern matching with C# programs.

Pattern Matching with “is” and “switch” Expression

Let’s illustrate pattern matching with “is” and “switch” expressions with the help of a below-provided example.

Example
The provided “using System” library is used at the top of the C# program to import the classes from the System namespace, such as Console, DateTime, or Math:

using System;

Now, we define a base class as “Color” and make a public function as “Show()” that simply prints a message on the screen as “Find a Color”:

class Color
{
    public virtual void Show()
    {
        Console.WriteLine("Find a Color");
    }
}

After that, we have a “Red” class which is referred to as the derived class that overrides the “Show()” method from the base class:

class Red : Color
{
    public override void Show()
    {
        Console.WriteLine("Find a Red Color");
    }
}

Then, inside the “Program” class, the static void “Main()” function has created an array of “Color” objects, including both instances of class “Color” and “Red”.

class Program
{
    static void Main()
    {
        Color[] colors = { new Color(), new Red() };

Moving forward, we use the “is” expression to determine the type of color whether each color is Red or not inside of the “foreach” loop. If so, it will print the “if” statement first and take particular steps. Otherwise, handle it as a regular shape.

        foreach (var color in colors)
        {
            if (color is Red red)
            {
                Console.WriteLine("It's a red color!");
                red.Show();
            }
            else
            {
                Console.WriteLine("It's not a red color!");
                color.Show();
            }

Next, we implement the “switch” expression to match the pattern type of “Red” with the “Color” case and perform actions accordingly. In the “switch” expression, the “default” case invokes when a pattern does not match with any particular type:

   // Using the 'switch' expression with type patterns
            switch (color)
            {
                case Red r:
                    Console.WriteLine("Switch: It's a Red Color");
                    r.Show();
                    break;
                default:
                    Console.WriteLine("Switch: It's not a Red Color!");
                    color.Show();
                    break;
            }
        }
    }
}

Output

You have learned pattern matching using “is” and “switch” expressions.

Conclusion

Pattern matching in C# is a versatile feature that is used to create code in more expressive ways. By leveraging pattern matching, you can make conditional logic simpler, extract data from intricate data structures, and make your code easier to read and maintain. The guide provided the usage of the “is” and “switch” expressions to check type patterns according to objects type in an effective way.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.