Switch expression in C# 12
The switch expression is a concise way to write a switch statement that returns a value. It is similar to the ternary operator, but it can handle multiple cases and patterns. For example, suppose we have an enum called Color that has three values: Red, Green, and Blue. We want to write a function that returns the name of the color as a string. We could use a switch statement like this:
string ColorName(Color color)
{
switch (color)
{
case Color.Red:
return "Red";
case Color.Green:
return "Green";
case Color.Blue:
return "Blue";
default:
throw new ArgumentException("Invalid color");
}
}
But with the switch expression, we can write the same function in one line:
string ColorName(Color color) => color switch
{
Color.Red => "Red",
Color.Green => "Green",
Color.Blue => "Blue",
_ => throw new ArgumentException("Invalid color")
};
As you can see, the switch expression uses the => operator to separate the case from the value, and the _ symbol to represent the default case. It also supports pattern matching, which allows us to check for more complex conditions. For example, suppose we have a class called Shape that has subclasses Circle, Square, and Triangle. We want to write a function that returns the area of the shape. We could use a switch expression like this:
double Area(Shape shape) => shape switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Square s => s.Side * s.Side,
Triangle t => t.Base * t.Height / 2,
null => 0,
_ => throw new ArgumentException("Invalid shape")
};
As you can see, we can use type patterns to match the shape to its subclass, and deconstruct it into a variable that we can use in the value expression. We can also use a constant pattern to match null values, and a discard pattern to match anything else.
The switch expression is a powerful and concise way to write conditional logic that returns a value. It can make your code more readable and maintainable.