Search code examples
c#switch-statementc#-8.0switch-expression

Is there a way for switch to return a string value using C# 8 switch expressions?


I have this code where each part of the switch returns a value to ModeMessage2. Is it possible using the new C# switch expressions (or any other code optimization) to optimize the way this switch works?

switch (Settings.Mode)
{
    case MO.Learn:
        ModeMessage2 =
            "Use this mode when you are first learning the phrases and their meanings.";
        if (Settings.Cc == CC.H)
        {
            Settings.Cc = CC.JLPT5;
            App.cardSetWithWordCount = null;
            App.DB.RemoveSelected();
        }
        break;
    case MO.Practice:
        ModeMessage2 =
             "Use this mode to help you memorize the phrases and their meanings.";
        if (Settings.Cc == CC.H)
        {
            Settings.Cc = CC.JLPT5;
            App.cardSetWithWordCount = null;
            App.DB.RemoveSelected();
        }
        break;
    case MO.Quiz:
        if (Settings.Cc == CC.H)
        {
            Settings.Cc = CC.JLPT5;
            App.cardSetWithWordCount = null;
            App.DB.RemoveSelected();
        }
        App.DB.UpdSet(SET.Adp, false);
        ModeMessage2 =
            "Use this mode to run a self marked test.";
        break;
}

Solution

  • Your code is similar to the following, though if there are side effects of setting ModeMessage2 or the other properties then the order that things happen might matter in which case this is not technically 100% equivalent.

    IList<MO> specialModes = new[] { MO.Learn, MO.Practice, MO.Quiz };
    
    if (specialModes.Contains(Settings.Mode) && Settings.Cc == CC.H) {
       Settings.Cc = CC.JLPT5;
       App.cardSetWithWordCount = null;
       App.DB.RemoveSelected();
    }
    
    ModeMessage2 = Settings.Mode switch {
       MO.Learn => "Use this mode when you are first learning the phrases and their meanings.",
       MO.Practice => "Use this mode to help you memorize the phrases and their meanings.",
       MO.Quiz => "Use this mode to run a self marked test.",
       _ => "Unknown mode value" // or throw
    };
    
    if (Settings.Mode == MO.Quiz)
       App.DB.UpdSet(SET.Adp, false);