Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

switch expression - pattern matching expressions using theswitch keyword

  • 2022-12-02
Feedback

In this article

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

The following example demonstrates aswitch expression, which converts values of anenum 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 aswitch expression:

  • An expression followed by theswitch keyword. In the preceding example, it's thedirection method parameter.
  • Theswitch expression arms, separated by commas. Eachswitch expression arm contains apattern, an optionalcase guard, the=> token, and anexpression.

At the preceding example, aswitch expression uses the following patterns:

  • Aconstant pattern: to handle the defined values of theDirection enumeration.
  • Adiscard pattern: to handle any integer value that doesn't have the corresponding member of theDirection enumeration (for example,(Direction)10). That makes theswitch expressionexhaustive.

Important

For information about the patterns supported by theswitch expression and more examples, seePatterns.

The result of aswitch expression is the value of the expression of the firstswitch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates totrue. Theswitch expression arms are evaluated in text order.

The compiler generates an error when a lowerswitch expression arm can't be chosen because a higherswitch 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 acase guard. Acase 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 thewhen 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 usesproperty patterns with nestedvar patterns.

Non-exhaustive switch expressions

If none of aswitch expression's patterns matches an input value, the runtime throws an exception. In .NET Core 3.0 and later versions, the exception is aSystem.Runtime.CompilerServices.SwitchExpressionException. In .NET Framework, the exception is anInvalidOperationException. In most cases, the compiler generates a warning if aswitch 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 aswitch expression handles all possible input values, provide aswitch expression arm with adiscard pattern.

C# language specification

For more information, see theswitch expression section of thefeature proposal note.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo