Reputation: 39
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
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
Action action = status switch { ...
)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