Switch
Apparence
Links
Exemple
switch (i)
{
case 1:
...
break;
case 2:
case 3:
...
goto case 1;
case 4:
...
goto default;
case 5:
...
return true;
case var x when x > 0 && x < 10:
...
return false;
default:
throw new ArgumentOutOfRangeException(nameof(i), i, "message");
throw new InvalidEnumArgumentException(nameof(i), (int)i, typeof(MyEnum));
throw new InvalidOperationException("message");
throw new NotSupportedException($"The value '{i}' is not supported.");
break;
}
// depuis VS 2017, switch accèpte d'autres types que int, char et string
switch (myObject)
{
case MyType1 object1: // si myObject est du type MyType1 → cast dans object1
break;
case MyType2 object2 when object2.MyProp > 0: // si myObject est du type MyType2 → cast dans object2 puis test object2.MyProp > 0
break;
}
|