C# switch
public static void test0()
{
int x = 2;
switch (x)
{
case 1:
Console.WriteLine("Un");
goto case 2;
case 2:
Console.WriteLine("Deux");
break;
default:
Console.WriteLine("Autre");
break;
}
}
// Switch avec goto
public static void test1()
{
int x = 2;
switch (x)
{
case 1:
Console.WriteLine("Un");
goto case 2;
case 2:
Console.WriteLine("Deux");
break;
default:
Console.WriteLine("Autre");
break;
}
}
// Switch expression
public static void test2()
{
int x = 1;
string result = x switch
{
1 => "Un",
2 => "Deux",
_ => "Autre"
};
Console.WriteLine(result);
}
// Pattern matching
public static void test3()
{
object obj = 52;
switch (obj)
{
case int i when i > 0:
Console.WriteLine($"Nombre positif : {i}");
break;
case string s:
Console.WriteLine($"Chaîne : {s}");
break;
case null:
Console.WriteLine("Null");
break;
default:
Console.WriteLine("Autre type");
break;
}
}
// Switch expression
public static void test4()
{
int x = 5;
string category = x switch
{
< 0 => "Négatif",
0 => "Zéro",
> 0 and < 10 => "Petit positif",
>= 10 => "Grand positif" //,
// _ => "Inconnu"
};
Console.WriteLine(category);
}
// Tuple patterns
public static void test5()
{
(int a, int b) pair = (1, 2);
string res = pair switch
{
(0, 0) => "Origine",
(1, _) => "X=1",
(_, 2) => "Y=2",
_ => "Autre"
};
Console.WriteLine(res);
}
// Property patterns
public static void test6()
{
var person = new { Name = "Jacques", Age = 42 };
string desc = person switch
{
{ Age: < 18 } => "Mineur",
{ Age: >= 18 and < 65 } => "Adulte",
{ Age: >= 65 } => "Senior",
_ => "Inconnu"
};
Console.WriteLine(desc);
}
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 test7()
{
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
}
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: int x1, Y: int y1 } when x1 < y1 => new Point(x1 + y1, y1),
{ 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),
};
public static void test8()
{
Point pin = new Point(0, 1);
Point pout = Transform(pin);
Console.WriteLine($"point: {pout.X} {pout.Y}");
}