'C# 8 switch expression: Handle multiple cases at once?
C# 8 introduced pattern matching, and I already found good places to use it, like this one:
private static GameType UpdateGameType(GameType gameType)
{
switch (gameType)
{
case GameType.RoyalBattleLegacy:
case GameType.RoyalBattleNew:
return GameType.RoyalBattle;
case GameType.FfaLegacy:
case GameType.FfaNew:
return GameType.Ffa;
default:
return gameType;
}
}
which then becomes
private static GameType UpdateGameType(GameType gameType) => gameType switch
{
GameType.RoyalBattleLegacy => GameType.RoyalBattle,
GameType.RoyalBattleNew => GameType.RoyalBattle,
GameType.FfaLegacy => GameType.Ffa,
GameType.FfaNew => GameType.Ffa,
_ => gameType;
};
However, you can see I now have to mention GameType.RoyalBattle and GameType.Ffa twice. Is there a way to handle multiple cases at once in pattern matching? I'm thinking of anything like this, but it is not valid syntax:
private static GameType UpdateGameType(GameType gameType) => gameType switch
{
GameType.RoyalBattleLegacy, GameType.RoyalBattleNew => GameType.RoyalBattle,
GameType.FfaLegacy, GameType.FfaNew => GameType.Ffa,
_ => gameType;
};
I also tried things like
[GameType.RoyalBattleLegacy, GameType.RoyalBattleNew] => GameType.RoyalBattle
or
GameType.FfaLegacy || GameType.FfaNew => GameType.Ffa
but none are valid.
Also did not find any example on this. Is it even supported?
Solution 1:[1]
You can eventually use var pattern combined with case guard (when clause). Not sure if it is better than the variant with duplicate return values, but here it is:
private static GameType UpdateGameType(GameType gameType) => gameType switch
{
var v when v == GameType.RoyalBattleLegacy || v == GameType.RoyalBattleNew
=> GameType.RoyalBattle,
var v when v == GameType.FfaLegacy || v == GameType.FfaNew
=> GameType.Ffa,
_ => gameType
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivan Stoev |
