Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string.Contains() with switch()

I'm doing an C# app where I use

if ((message.Contains("test"))) {    Console.WriteLine("yes"); } else if ((message.Contains("test2"))) {    Console.WriteLine("yes for test2"); } 

There would be any way to change to switch() the if() statements?

like image 367
pmerino Avatar asked Aug 24 '11 12:08

pmerino


People also ask

Can switch case contains String?

Yes, we can use a switch statement with Strings in Java.

Can we use contains in switch case Java?

You can't switch on conditions like x. contains() . Java 7 supports switch on Strings but not like you want it.

How do you match a String in a switch case?

To ensure that we have a match in a case clause, we will test the original str value (that is provided to the switch statement) against the input property of a successful match . input is a static property of regular expressions that contains the original input string. When match fails it returns null .

Can I use && in switch?

The simple answer is No. You cant use it like that. Switch works with single expression.


1 Answers

Correct final syntax for [Mr. C]s answer.

With the release of VS2017RC and its C#7 support it works this way:

switch(message) {     case string a when a.Contains("test2"): return "no";     case string b when b.Contains("test"): return "yes"; } 

You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.

like image 64
Lakedaimon Avatar answered Sep 22 '22 01:09

Lakedaimon