Using C# 7 Pattern Matching

C# has long been one of the most popular languages for developing Web and Windows applications alike. C# 7 comes with a lot of new features and enhancements, with special focus on simplification of code, easier consumption of data, and improved performance. Pattern matching is one of the great new features introduced in C# 7. Pattern matching is a feature that has been introduced in C# 7. This article presents a discussion on pattern matching in C# 7 and how to work with it.

What’s Pattern Matching and How Does It Help?

You can perform pattern matching by using the “is” expression and also by using the “switch-case” constructs. You can use patterns in “is” and “switch” statements. Moreover, you can match patterns with any data type, even custom data types. In essence, pattern matching is a feature that enables you to test a value and then extract information out of it if the pattern under test is a success. You can take advantage of this feature to match patterns on any data type, even on custom data types.

Pattern Matching at Work

The patterns that are supported in C# 7 include Constant patterns, Type patterns, and Var patterns. Here’s a simple example that illustrates how you can work with the constant pattern. Consider the following class, Student.

public class Student
   {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public Student(string firstName, string lastName)
      {
         FirstName = firstName;
         LastName = lastName;
      }
   }

Here’s how you can check for a constant pattern by checking if the value is null.

static void Main(string[] args)
   {
      object[] records = { null, new Student("Joydip",
         "Kanjilal") };
      foreach (var item in records)
      {
         CheckConstantPattern(item);
      }
      Console.ReadKey();
   }

The CheckConstantPattern method is given in the next code snippet.

public static void CheckConstantPattern(object obj)
   {
      if (obj is null)
      Console.WriteLine("This is a constant pattern");
   }

Let’s now understand how the Type pattern works. Here is an example that illustrates how the “is” expression can be used to match patterns using C# 7. Consider the following three classes, namely, Employee, SalariedEmployee, and WagedEmployee.

public abstract class Employee
   {
      // Write your code here
   }
   public class SalariedEmployee : Employee
   {
      // Write your code here
   }
   public class WagedEmployee : Employee
   {
      // Write your code here
  }

You now can use the “is” expression to check the type of an object, as shown in the next code snippet.

static void Main(string[] args)
   {
      Employee emp = new SalariedEmployee();
      if(emp is SalariedEmployee)
      {
         Console.WriteLine("The emp object is
            of type SalariedEmployee");
      }
      Console.ReadKey();
   }

When you execute the preceding code snippet, the message “The emp object is of type SalariedEmployee” is displayed in the console window.

You also can take advantage of the switch statement to check for constant or type patterns in your code. The following code snippet illustrates how this can be achieved.

Student student = new Student("Joydip", "Kanjilal");
   switch (student)
   {
      case null:
         Console.WriteLine("This is a constant pattern");
         break;
      case Student s when s.FirstName.StartsWith("J"):
         Console.WriteLine(s.FirstName);
         break;
      case var x:
         Console.WriteLine("This is a var pattern with the
            type {x?.GetType().Name} ");
         break;
      default:
         break;
   }

And lastly, you have another pattern to test for—it’s the Var pattern. Let’s now understand how the Var pattern works. The Var pattern is always successful as long as the object is of a particular type. The following code snippet illustrates how you can use this pattern in your code.

Employee emp = new SalariedEmployee();
   if (emp is var x)
      Console.WriteLine("This is a var pattern with the
         type {x?.GetType()?.Name}");
Note: If the object emp is null, the GetType method would throw a NullReferenceException because the null conditional operator has been used here.

Summary

Pattern matching is a great feature that borrows its ideas from functional programming and helps you simplify and reduce your code. This article presented a discussion on one of the most striking features in C# 7—pattern matching—and how we can work with it with relevant code examples wherever necessary. Happy reading!

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read