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

How do I declare parameters returned from a C# 8 switch expression?


I am looking at this code:

public enum MO
{
    Learn, Practice, Quiz
}

public enum CC
{ 
    H
}

public class SomeSettings
{
    public MO Mode { get; set; }
    public CC Cc { get; set; }
}

static void Main(string[] args)
{
    var Settings = new SomeSettings() { Cc = CC.H, Mode = MO.Practice };

    var (msg,isCC,upd) = Settings.Mode switch {
        case MO.Learn => ("Use this mode when you are first learning the phrases and their meanings.",
                          Settings.Cc == CC.H,
                          false),
        case MO.Practice => ("Use this mode to help you memorize the phrases and their meanings.",
                          Settings.Cc == CC.H,
                          false),
        case MO.Quiz => ("Use this mode to run a self marked test.",
                          Settings.Cc == CC.H,
                          true);
        _ => default;
    }
}

Unfortunately it seems that the msg, isCC and upd are not declared correctly and it gives a message saying this:

Cannot infer the type of implicitly-typed deconstruction variable 'msg' and the same for isCC and upd.

Can you help explain to me how I can declare these?


Solution

  • case labels are not used with switch expressions, you have a ; in the middle, and no ; after:

    var (msg, isCC, upd) = Settings.Mode switch {
        MO.Learn => ("Use this mode when you are first learning the phrases and their meanings.",
                            Settings.Cc == CC.H,
                            false),
        MO.Practice => ("Use this mode to help you memorize the phrases and their meanings.",
                            Settings.Cc == CC.H,
                            false),
        MO.Quiz => ("Use this mode to run a self marked test.",
                            Settings.Cc == CC.H,
                            true),
        _ => default
    };