Ray
Ray

Reputation: 8881

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?

Upvotes: 3

Views: 2657

Answers (2)

MarredCheese
MarredCheese

Reputation: 20891

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:

Upvotes: 7

Ivan Stoev
Ivan Stoev

Reputation: 205849

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
};

Upvotes: 5

Related Questions