Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Switch If condition to expand the switch cases

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 
    }
}
like image 955
Luuke Avatar asked Nov 30 '22 07:11

Luuke


2 Answers

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 case statements need not be mutually exclusive, you can add a when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value.

like image 62
Pavel Anikhouski Avatar answered Dec 08 '22 18:12

Pavel Anikhouski


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 
    }
}
like image 45
Martin Avatar answered Dec 08 '22 17:12

Martin