0
Case invalid expression term
Whatâs wrong with this switch case statement? It throws: âinvalid expression term <â profit is an integer. switch(profit) { case == 0: Console.WriteLine("Broke Even"); break; case < 0: Console.WriteLine("Loss"); break; case > 0: Console.WriteLine("Profit"); break; default: Console.WriteLine("Sum ting wong"); break; }
6 Answers
+ 6
1) You can't use conditional checking inside a switch case, you can only use numbers like the below snippet:
switch(profit){
case 0:
Console.WriteLine("Broke even");
break;
.....
}
Also as a side note, to check if a variable is equal to a value, use == and not =. = is only used to assign a value to a variable.
+ 2
You might find switch expression helpful for these types of scenario. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
But I personally would prefer use of `if...else if...else` where exists a possibility that condition(s) are involved in evaluation, more compatible disregarding the programming language selection.
+ 2
If you wish, you can combine đ:
switch(profit){
case 0:
Console.WriteLine("Broke Even");
break;
default:
if(profit < 0)
Console.WriteLine("Loss");
else if(profit > 0)
Console.WriteLine("Profit");
else
Console.WriteLine("Sum ting wong");
break;
}
+ 2
Referring to MS Docs it should be possible to use conditional checking on cases.
I tried to run the example code on the playground and received the same error.
Just found out, that pattern matching is released with c# 7.0
C# 6.0 and earlier doesnât support this feature.
https://docs.microsoft.com/de-de/dotnet/csharp/language-reference/statements/selection-statements
+ 2
Yes, the new version of C# has expanded the functionality a lot. âșïž
+ 1
You may try something like this
try {
switch (profit/Math.Abs(profit))
{
case 1:
Console.WriteLine("Profit");
break;
case -1:
Console.WriteLine("Loss");
break;
default :
Console.WriteLine("Something wrong!");
break;
}
}
catch (DivideByZeroException e) {
Console.WriteLine("Broke Even");
}