# switch 運算式 (c # 參考)

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)}");
// Output:
// Map view direction is Right
// Cardinal orientation is East
}
}


• 後面接著關鍵字的運算式 switch 。 在上述範例中，它是 direction 方法參數。
• switch 運算式臂（以逗號分隔）。 每個 switch 運算式 arm 都包含一個 模式，也就是選擇性的 案例防護=> token 和 運算式

• 常數模式，用來處理已定義的 Direction 列舉值。
• 捨棄模式，用來處理任何沒有列舉對應成員的整數值 Direction (例如 (Direction)10) 。 這會讓 switch 運算式 詳盡

## 案例防護

public readonly struct Point
{
public Point(int x, int y) => (X, Y) = (x, y);

public int X { get; }
public int Y { get; }
}

static Point Transform(Point point) => point switch
{
{ X: 0, Y: 0 }                    => new Point(0, 0),
{ X: var x, Y: var y } when x < y => new Point(x + y, y),
{ X: var x, Y: var y } when x > y => new Point(x - y, y),
{ X: var x, Y: var y }            => new Point(2 * x, 2 * y),
};