C# 7.0 : Pattern Matching

In one of the previous blog post , we saw the Out variables enhancements in C# 7.0. This blog post will explain one of the new features in C# 7.0 called Pattern matching and how developers can leverage its capabilities.

In simple terms , pattern matching refers to match a value to certain shape and extract certain information from the value.

In C# 7.0 , patterns are applied to the two existing language feature that includes

  • is expression
  • switch statement

“is” expression with pattern matching

Here’s an example of the is expression with pattern matching.

using System;
namespace DeveloperPublisConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Welcome to DeveloperPublish.com";
            Demo1(input);
            Console.ReadLine();
        }
        public static void Demo1(object input)
        {
            if (input is null)
                Console.WriteLine(input);
            // Check if the input is of type string , if yes , extract the value to tempStr
            if (input is string tempStr)
                Console.WriteLine(tempStr);
        }
       
    }
}

image

In the above example , the variable tempStr which is declared by the pattern is similar to the behavior of out variable and is made available to the surrounding scope.

Switch Statement and Patterns

C# 7.0 brings in the feature of patterns to the switch statements and thus adds some cool features that removes the restrictions that we had with the switch statement in the current version.

For example , you can now switch on not only the primitive type but on any type with C# 7.0. Additionally , you can combine the patterns with the case clause. The Current version of C# (C#6.0 and earlier) had the restriction where you need to specify the constant value for the case clause.

Here’s an example of the Switch Statement and Patterns.

Assume that you have the class Circle and Rectangle that extends the interface IShape.

public interface IShape
{

}
public class Circle : IShape
{
}
public class Rectangle : IShape
{
    public int Length { get; set; }
}

The method Demo2 takes the parameter of type IShape and demonstrates the usage of the switch statement on the IShape type as well as usage of the patterns in the case clause with the conditions too. Note that the order of the case clause is very important in this case because of simple reason that the first case that matches the conditions will be picked.

The default clause is always evaluated in the last in spite of having the null clause check.

public static void Demo2(IShape shape)
{            
    switch(shape)
    {
        case Circle c:
            Console.WriteLine("This is a Circle");
            break;
        case Rectangle r when (r.Length > 4):
            Console.WriteLine("This is a Rectangle with length greater than 4");
            break;
        case Rectangle r:
            Console.WriteLine("Rectangle R");
            break;
        case null:
            break;
        default :
            break;
    }
}

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...