I admit it, I’ve struggled with pattern matching. In the next few blog posts I’ll explore this magic, starting today with switch expressions (not to be confused with switch statements).
The type of switch we’re familiar with is the switch statement:
namespace switchStatement;
internal class Program
{
static void Main(string[] args)
{
string day = string.Empty;
day = GetDay(2);
Console.WriteLine(day);
}
public static string GetDay(int dayNum)
{
string dayName;
switch (dayNum)
{
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid day number";
break;
}
return dayName;
}
}
This will return Tuesday.
A switch expression has a slightly different syntax, but more important, it matches on a pattern. I’m going to use the example from Microsoft Learning (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression) and take it apart
public static class SwitchExample
{
public enum Direction
{
Up,
Down,
Right,
Left
}
public enum Orientation
{
North,
South,
East,
West
}
public static Orientation ToOrientation(Direction direction) => direction switch
{
Direction.Up => Orientation.North,
Direction.Right => Orientation.East,
Direction.Down => Orientation.South,
Direction.Left => Orientation.West,
_ => throw new ArgumentOutOfRangeException(nameof(direction), $"Not expected direction value: {direction}"),
};
public static void Main()
{
var direction = Direction.Right;
Console.WriteLine($"Map view direction is {direction}");
Console.WriteLine($"Cardinal orientation is {ToOrientation(direction)}");
}
}
The output of this is
Map view direction is Right
Cardinal orientation is East
The method ToOrientation takes a Direction and calls the switch expression (notice the placement of the keyword switch).
It then sets up the Direction to Orientation pattern matching. For example, it establishes that if the passed in parameter is Direction.Up (that is, the Up enumerated constant) then it is to be converted to Orientation.North, and so forth. (The underscore is a new way of indicating no value, or in this case, the default).
The various expressions are called “arms” and are separated by commas. Each arm contains a pattern and an expression. In the first arm, Direction.Up returns the expression Orientation.North.
It is this pattern matching that I’ll be exploring in the next few blog posts.