I'm working on a Switch statement and with two of the conditions I need to see if the values start with a specific value. The Switch statement does like this. The error says "cannot covert type bool to string".
Anyone know if I can use the StartsWith in a Switch or do I need to use If...Else statements?
switch(subArea) { case "4100": case "4101": case "4102": case "4200": return "ABC"; case "600A": return "XWZ"; case subArea.StartsWith("3*"): case subArea.StartsWith("03*"): return "123"; default: return "ABCXYZ123"; }
The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value. The value of the 'expression' in a switch-case statement must be an integer, char, short, long. Float and double are not allowed.
The simple answer is No. You cant use it like that.
An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value. Also, the value provided to each case statement must be unique.
If a matching value is found, control is passed to the statement following the case label that contains the matching value. If there is no matching value but there is a default label in the switch body, control passes to the default labelled statement.
Since C# 7 you can do the following:
switch(subArea) { case "4100": case "4101": case "4102": case "4200": return "ABC"; case "600A": return "XWZ"; case string s when s.StartsWith("3*"): return "123"; case string s when s.StartsWith("03*"): return "123"; default: return "ABCXYZ123"; }
EDIT: If you are using C# >= 7, take a look at this answer first.
You are switching a String
, and subArea.StartsWith()
returns a Boolean
, that's why you can't do it. I suggest you do it like this:
if (subArea.StartsWith("3*") || subArea.StartsWith("03*")) return "123"; switch(subArea) { case "4100": case "4101": case "4102": case "4200": return "ABC"; case "600A": return "XWZ"; default: return "ABCXYZ123"; }
The result will be the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With