Build algorithms with pattern matching | Real World Example

In this post I will show you a very powerfull feature of C# 9.0 pattern matching. Pattern matching provides more concise syntax for algorithms you already use today. You already create pattern matching algorithms using existing syntax. You write if or switch statements that test values

Let’s take a look at the FizzBuzz problem, which is a common interview question. I’ll start by writing the code in switch statements, then convert it to pattern matching.


void Main()
{
	FizzBuzzSwitchCase();
}

public void FizzBuzzSwitchCase()
{
	for (int i = 0; i <= 10000; i++)
	{
		FizzBuzzSwitchCase(i);
		
	}
}

public void FizzBuzzSwitchCase(int i)
{
	switch (true)
	{
		case var FizzBuzz when (i % 15 == 0):
			Console.WriteLine("fizzbuzz");
			break;
		case var Fizz when (i % 3 == 0):
			Console.WriteLine("fizz");
			break;
		case var Buzz when (i % 5 == 0):
			Console.WriteLine("buzz");
			break;
		default:
			Console.WriteLine(i);
			break;
	}
}

Let’s now translate the switch statement to a pattern matching statement. Here’s the code: The syntax I’m using is pattern matching. Let’s take a closer look at each line

  • If all conditions are satisfied, the outcome is (0,0).
  • (0,_) if the first condition is met (ignore second one)
  • (_,0) If the second condition is met
  • _ if none of them are matching
void FizzBuzzUsingPatternMatch(int i)
{
	var result= (i % 3, i % 5) switch
	{
		(0, 0) => "fizzbuzz",
		(0, _) => "fizz",
		(_, 0) => "buzz",
		_ => i.ToString()

	};
	Console.WriteLine(result);
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post