Introduction

Pattern matching has been introduced in C# 6 and has well evolved since. The latest improvement was pretty interesting on C# 8 which has been released last year. If you missed pattern matching improvements on C# 8 , here is a nice article from Miguel Bernard (@MiguelBernard88): https://blog.miguelbernard.com/pattern-matching-in-csharp/. If you have missed all new features in C# 8, you can read also his great serie here: https://blog.miguelbernard.com/csharp-8-0-new-features/.

In this article I will show you all the great new features of pattern matching.

Relational patterns

C# 9 allows you to use relational pattern which enables the use of <, >, <= and >= in patterns like this:

using CSharp9Demo.Models;
	using System;

	namespace CSharp9Demo
	{
	    class Program
	    {
	        static void Main(string[] args)
	        {
	            var product = new Product { Name = "Food", CategoryId = 4 };
		    GetTax(product); // Returns 5
	        }

	        // Relational pattern
	        private static int GetTax (Product p) => p.CategoryId switch
	        {
	            1 => 0,
	            < 5 => 5,
	            > 20 => 15,
	            _ => 10
	        };
	    }

	    public class Product
	    {
	        public string Name { get; set; }
	        public int CategoryId { get; set; }
	    }

	    public class Book : Product
	    {
	        public string ISBN { get; get; }
	    }

	    public class ElectronicProduct : Product
	    {
		public bool HasBluetooth { get; set; }
	    }
	}

#.net 5 #csharp #csharp 9 #programming-c

Introducing C# 9: Improved pattern matching
5.70 GEEK