Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .StartsWith in a Switch statement?

Tags:

c#

.net

asp.net

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";             } 
like image 240
Caverman Avatar asked Jan 22 '16 17:01

Caverman


People also ask

What Cannot be used in a switch statement?

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.

Can you use && in a switch statement?

The simple answer is No. You cant use it like that.

Can switch statements use integers?

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.

What will happen if there is a match in a switch statement?

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.


2 Answers

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"; } 
like image 50
PWR460 Avatar answered Sep 20 '22 05:09

PWR460


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.

like image 35
appa yip yip Avatar answered Sep 19 '22 05:09

appa yip yip