I have some data which need to converted, for that I need a switch condition with more than 50 cases, I need the same cases 3 times but in the third time I need the 50 cases and some more and I don't want to write the same code twice. Maybe there is a possibility to do something like this.
switch (example)
{
case "1":
//do something
case "2":
//do something
case "50":
//do something
//now maybe something like this
if (condition == true)
{
case "1":
//do something else than above at case "1", and so on
//now its i little bit illogical, but i neet to do the first 50 cases and then
//use the cases 1 to 50 again but with other actions
}
}
Starting from C# 7 you can combine the case statement with when clause and use it to simplify your code a little bit
switch (example)
{
case "1":
//do something
case "2":
//do something
case "50":
//do something
//now maybe something like this
case "51" when condition == true:
//do something, and so on
default:
break;
}
Starting with C# 7.0, because
casestatements need not be mutually exclusive, you can add awhenclause to specify an additional condition that must be satisfied for thecasestatement to evaluate to true. Thewhenclause can be any expression that returns aBooleanvalue.
I presume you are looking for a way not to repeat if (condition == true). Aside from the new when clause in C#7, you could also take a different approach with two switch statements:
if (!condition)
{
switch (example)
{
case "1":
//do something
case "2":
//do something
case "50":
//do something
}
} else {
switch (example)
{
case "51:
//do something, and so on
}
}
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