Simple Pattern Matching with a Switch Expression in C#
c#Recently having learned about pattern matching in C#, I was thinking of ways to incorporate it into my code. I came across a function that seemed like a good candidate to try it on. The function takes in a string and then returns a "cleaned" version of it so that we don’t have all sorts of variants.
public static string GetCleanedName(string fruit)
{
if (fruit.Contains("Apple"))
{
return "Apple";
}
if (fruit.Contains("Pear"))
{
return "Pear";
}
if (fruit == "Peech")
{
return "Peach";
}
return fruit;
}
Changing it to a switch expression made it much more concise.
public static string GetCleanedName(string fruit)
{
fruit = fruit switch
{
string s when s.Contains("Apple") => "Apple",
string s when s.Contains("Pear") => "Pear",
"Peech" => "Peach",
_ => fruit
};
return fruit;
}
To make it even more concise, you can turn the function into an expression statement.
public static string GetCleanedName(string fruit) =>
fruit switch
{
string s when s.Contains("Apple") => "Apple",
string s when s.Contains("Pear") => "Pear",
"Peech" => "Peach",
_ => fruit
};
In action, you would have something like this:
using System;
using System.Collections.Generic;
class Program {
public static void Main (string[] args) {
List<string> fruits = new List<string> {"Green Apple", "Asian Pear", "Peech", "Kiwi"};
foreach(var fruit in fruits)
{
Console.WriteLine($"'{fruit}' becomes '{GetCleanedName(fruit)}'.");
}
}
public static string GetCleanedName(string fruit) =>
fruit switch
{
string s when s.Contains("Apple") => "Apple",
string s when s.Contains("Pear") => "Pear",
"Peech" => "Peach",
_ => fruit
};
public static string GetCleanedNameOldVersion(string fruit)
{
if (fruit.Contains("Apple"))
{
return "Apple";
}
if (fruit.Contains("Pear"))
{
return "Pear";
}
if (fruit == "Peech")
{
return "Peach";
}
return fruit;
}
}