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?
As of C#9, you can do exactly what you wanted via "disjunctive or
" patterns:
private static GameType UpdateGameType(GameType gameType) => gameType switch
{
GameType.RoyalBattleLegacy or GameType.RoyalBattleNew => GameType.RoyalBattle,
GameType.FfaLegacy or GameType.FfaNew => GameType.Ffa,
_ => gameType;
};
Further reading: