Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of performing some code within a Switch statement that executes only if any of the cases have been passed?

Is there a way that I can execute the same line of code for each "Case" but only have to type it in once instead of having the same code specified for all Cases ?

        switch (SomeTest)
        {
            case "test1":
                {
                    // Do something for test 1 
                    break;
                }
            case "test2":
                {
                    // Do something for test 2 
                    break;
                }
            case "test3":
                {
                    // Do something for test 3 
                    break;
                }
            // =====> Then do something generic here for example if case is test1, test2 or test3
        }
like image 476
cyberbobcat Avatar asked Oct 19 '25 12:10

cyberbobcat


1 Answers

Are you possibly over thinking it?

switch(SomeTest)
{
    // specific stuff
}

// code you want running for every case

Otherwise the best you can do without setting a flag or something is:

switch(SomeTest)
{
    // specific stuff
}

switch(SomeTest)
{
    case "Test1", "Test2", "Test3":
        // stuff for the matching cases
}

Or if you want to run the code for every case you match:

bool runGenericStuff = true;

switch(SomeTest)
{
    // specific stuff
    default:
        runGenericStuff = false;
}

if (runGenericStuff)
{
    // run generic stuff
}

That saves you having to set the flag in every case.

like image 83
Garry Shutler Avatar answered Oct 22 '25 01:10

Garry Shutler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!