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!



About the Author

Joydip Kanjilal

Joydip Kanjilal is a Microsoft Most Valuable Professional in ASP.Net, as well as a speaker and the author of several books and articles. He received the prestigious MVP (Most Valuable Professional) award at ASP.Net for 2007, 2008, 2009, 2010, 2011, and 2012. He has more than 18 years of industry experience in IT, with more than 14 years in Microsoft .Net and its related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times. He is the author of eight books and more than 300 articles. He was a speaker a speaker at the reputed Spark IT 2010 event and at the reputed Dr. Dobb’s Conference 2014 in Bangalore. He is also a regular speaker at SSWUG Virtual Conference. He's also worked as a judge for the Jolt Awards at Dr. Dobb's Journal.

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date