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?
Yes, we can use a switch statement with Strings in Java.
You can't switch on conditions like x. contains() . Java 7 supports switch on Strings but not like you want it.
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 .
The simple answer is No. You cant use it like that. Switch works with single expression.
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.
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