Pattern matching using C# Switch expressions
Switch expressions pattern matching provides developers with a concise and expressive way to handle complex conditional logic. It allows you to match patterns within a switch expression, rather than just values.
One of the key benefits of switch expressions pattern matching is that it reduces the amount of code you need to write to handle different cases. This can make your code more readable, maintainable, and efficient.
Here's an example of how you can use switch expressions pattern matching in C#:
public string Execute(ICommand command) => (command) switch
{
OpenCommand o => "Open Command",
CloseCommand o => "Close Command",
ExecuteCommand o => "Execute Command",
_ => throw new ArgumentOutOfRangeException(nameof(command), command, null)
};
In the above example, we define a method called Execute that takes an ICommand object as a parameter. We then use a switch expression to match the type of the command and return the corresponding action. Also it is far easier to use pattern matching on the properties of the paratmers.
public string Execute(ICommand command) => (command) switch
{
{ Valid: true } and {Value: > 10 }=> "Open Command",
{ Valid: false } and {Value: <= 10 } => "Close Command",
ExecuteCommand o => "Execute Command",
_ => throw new ArgumentOutOfRangeException(nameof(command), command, null)
};
The switch expression uses the arrow notation (=>) to match the pattern and return the result. The _ symbol acts as a catch-all case, which throws an exception if an invalid command is passed in.
Tuples significantly improves the pattern matching as shown in the below example.
private static string FormatMobileNumber(string number) =>
(number.StartsWith("+6"), number.StartsWith("6"), number.StartsWith("04")) switch
{
(true, _, _) => number,
(false, true, _) => $"+61{number[1..]}",
(false, false, true) => $"+61{number[1..]}",
_ => number
};
Overall, switch expressions pattern matching is a powerful feature in C# that can help you write more expressive and maintainable code. Whether you're working on a small project or a large enterprise application, it's definitely worth considering using switch expressions pattern matching in your code.