switch-case
statement in C#. switch-case
statement is used to evaluate an expression and execute a block of code based on the result of the evaluation. The basic syntax of the switch-case
statement is as follows:switch (expression)
{
case value1:
// code to execute when expression is equal to value1
break;
case value2:
// code to execute when expression is equal to value2
break;
// more cases can be added here
default:
// code to execute when expression doesn't match any of the cases
break;
}
switch-case
statement can be used in a class:public class MyClass
{
public void ProcessValue(int value)
{
switch (value)
{
case 1:
Console.WriteLine("Value is 1");
break;
case 2:
Console.WriteLine("Value is 2");
break;
case 3:
Console.WriteLine("Value is 3");
break;
default:
Console.WriteLine("Value is not 1, 2 or 3");
break;
}
}
}
ProcessValue
method takes an integer value as input and uses the switch-case
statement to determine what to do based on the value. If the value is 1, 2 or 3, the method will output a message indicating that the value is 1, 2 or 3 respectively. If the value is not 1, 2 or 3, the method will output a message indicating that the value is not 1, 2 or 3.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 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),
};