A lot of the examples of switch expressions you can find are where a function directly maps to an expression. For example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"), | |
}; |
This could make you think that you cannot use a switch expression inside a method body. It certainly is possible. The only important thing is that you assign the result of your switch expression to a variable. Letās rewrite the example above:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Orientation ToOrientation(Direction direction) | |
{ | |
var orientation=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}"), | |
}; | |
return orientation; | |
} |