A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression below:

switch expression - Evaluate a pattern match expression using the `switch` expression - C# reference

You use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression. For information about the switch statement that supports switch-like semantics in a statement context, see the switch statement section of the Selection statements article.

The following example demonstrates a switch expression, which converts values of an enum representing visual directions in an online map to the corresponding cardinal directions:

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
    }
}

The preceding example shows the basic elements of a switch expression:

At the preceding example, a switch expression uses the following patterns:

Important

For information about the patterns supported by the switch expression and more examples, see Patterns.

The result of a switch expression is the value of the expression of the first switch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates to true. The switch expression arms are evaluated in text order.

The compiler generates an error when a lower switch expression arm can't be chosen because a higher switch expression arm matches all its values.

Case guards

A pattern may be not expressive enough to specify the condition for the evaluation of an arm's expression. In such a case, you can use a case guard. A case guard is another condition that must be satisfied together with a matched pattern. A case guard must be a Boolean expression. You specify a case guard after the when keyword that follows a pattern, as the following example shows:

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),
};

The preceding example uses property patterns with nested var patterns.

Non-exhaustive switch expressions

If none of a switch expression's patterns matches an input value, the runtime throws an exception. In .NET Core 3.0 and later versions, the exception is a System.Runtime.CompilerServices.SwitchExpressionException. In .NET Framework, the exception is an InvalidOperationException. In most cases, the compiler generates a warning if a switch expression doesn't handle all possible input values. List patterns don't generate a warning when all possible inputs aren't handled.

Tip

To guarantee that a switch expression handles all possible input values, provide a switch expression arm with a discard pattern.

C# language specification

For more information, see the switch expression section of the feature proposal note.

See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.3