3

I have this code which I refactored to use a switch but it still looks very clumsy. Now I am looking for a way to simplify it.

    public async Task CheckAvailability()
    {
        switch (Settings.Mode)
        {
            case Enums.MO.Learn:
                if (await IsLearn())
                {
                    await ShowFirstMessageAsync();
                    return;
                }
                break;
            case Enums.MO.Practice:
                if (await IsPractice())
                {
                    await ShowFirstMessageAsync();
                    return;
                }
                break;
            case Enums.MO.Quiz:
                if (await IsQuiz())
                {
                    await ShowFirstMessageAsync();
                    return;
                }
                break;
            default:
                break;
        }

        await PickCard();
    }

Is there anyone that can think of a simpler way to implement this without the need for multiple calls to await ShowFirstMessageAsync?

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

11

This is a good opportunity to use switch expressions in C# 8:

var shouldShowFirstMessage = Settings.Mode switch
{
    Enums.MO.Learn => await IsLearn(),
    Enums.MO.Practice => await IsPractice(),
    Enums.MO.Quiz => await IsQuiz(),
    _ => false
}
if (shouldShowFirstMessage) {
    await ShowFirstMessageAsync();
} else {
    await PickCard();
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Very impressive ! – Alan2 Nov 21 '19 at 13:43
  • Just upgraded to C# 8 and testing this out now. I will try to use expressions more often and hopefully your answer will be a good help to others who have been wondering how they could be used. – Alan2 Nov 21 '19 at 13:54
2

Maybe this:

public async Task CheckAvailability()
{
    bool showFirstMessage = false;
    switch (Settings.Mode)
    {
        case Enums.MO.Learn:
            showFirstMessage = await IsLearn();
            break;
        case Enums.MO.Practice:
            showFirstMessage = await IsPractice();
            break;
        case Enums.MO.Quiz:
            showFirstMessage = await IsQuiz();
            break;
        default:
            break;
    }

    if (showFirstMessage)
    {
        await ShowFirstMessageAsync();
        return;
    }

    await PickCard();
}
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35