user10829672
user10829672

Reputation: 39

using multiple statements in switch expression is giving CS0201 error

Below C# switch expression is giving Compiler Error

CS0201 Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Not sure what is wrong here? In this case need to add multiple statements for each case.

status switch
{
    "ANY" => () =>
    {
        checkboxUtils.TickCheckbox(name, status);
        return;
    }
    ,
    "true" => () =>
    {
        if (!(bool)ChecksCkeckboxIsChecked(name, status))
            checkboxUtils.TickCheckbox(name, status);
    }
    ,
    "false" => () =>
    {
        if ((bool)ChecksCkeckboxIsChecked(name, status))
            checkboxUtils.TickCheckbox(name, status);
    }
    ,
    _ => () =>
    {
        DriverContext.Driver.Wait(1);
        checkboxUtils.TickCheckbox(name, status);
        DriverContext.Driver.Wait(2);

        if (!(bool)ChecksCkeckboxIsChecked(name, status))
        {
            testUtilsSteps.ThenUserRefreshesThePage();
            continue;
        }
    }
};

Upvotes: -2

Views: 116

Answers (1)

gunr2171
gunr2171

Reputation: 17579

You're using a switch expression. The switch must return a value (and be assigned to something), hence your error.

Don't use them, it's wholly inappropriate for your use case. Instead, use a switch statement.

switch (status)
{
    case "ANY":
        checkboxUtils.TickCheckbox(name, status);
        return;
    case "true":
        if (!(bool)ChecksCkeckboxIsChecked(name, status))
            checkboxUtils.TickCheckbox(name, status);
        break;
    // ... the rest
}

The only reason you'd want to use a switch expression is if you were creating an Action variable to execute later. In order to do that you'd need to

  1. You must assign the value of the switch expression to a variable (Action action = status switch { ...)
  2. Each "case" in your switch must return the same type. It looks like you're doing a void Action. This means you cannot use the continue keyword, and return simply means to return early from the anonymous function, not the outer context.

Really, don't try to hack using switch expressions, use the right tool for this job.

Upvotes: 2

Related Questions