3

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?

Ray
  • 7,940
  • 7
  • 58
  • 90

2 Answers2

5

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
};
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • That's probably the best solution for now, even if a bit unreadable (C#'s fault). Not sure if I'll actually use it in the source, but this answers my question nicely. :) – Ray Jul 07 '19 at 12:54
  • You don't need to assign to a variable v since you are doing nothing with it. It just can be `_ when gameType == GameType.RoyalBattleLegacy || gameType == GameType.RoyalBattleNew` – Eli Feb 07 '20 at 17:58
5

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:

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
  • You're absolutely right! Indeed I've been using it since it was introduced, good call to add a newer answer here. – Ray Feb 12 '22 at 00:04