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; }

4th Mar 2022, 12:18 AM
Marco Hall
Marco Hall - avatar
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.
4th Mar 2022, 12:51 AM
Rishi
Rishi - avatar
+ 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.
4th Mar 2022, 1:29 AM
Ipang
+ 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; }
4th Mar 2022, 3:03 AM
Solo
Solo - avatar
+ 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
4th Mar 2022, 7:07 PM
Marco Hall
Marco Hall - avatar
+ 2
Yes, the new version of C# has expanded the functionality a lot. â˜ș
4th Mar 2022, 7:50 PM
Solo
Solo - avatar
+ 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"); }
4th Mar 2022, 3:12 AM
Simba
Simba - avatar