Let's say I have 5 boolean values:

bool a;
bool b;
bool c;
bool d;
bool e;

If they evaluate as true 'a', 'b', 'c' and 'd' should have their associated code run. If 'e' evaluates as true then only its associated code is run and the values of 'a', 'b', 'c' and 'd' ignored.

How then can I put this logic into a switch case statement? It is straight forward with nested if statements but I would like to know if there is a way to do it with switch/case.

Not really. Switch/case is designed to operate off one variable, not five. You could do it, but it would look ugly. Something like this:

switch (e) {
    case true: eMethod(); break;
    case false:
        switch (a) {
            case true: aMethod(); break;
            default: break;
        switch (b) {
            case true: bMethod(); break;
            default: break;
        switch (c) {
            case true: cMethod(); break;
            default: break;
        switch (d) {
            case true: dMethod(); break;
            default: break;

As a matter of personal taste, I request you don't use switch/case. If statements would be a lot cleared and would reduce nesting to a degree.

Also, if you have output, you can use a ternary operator

    myVal = a ? aMethod() : defaultValue;
    myVal2 = b ? bMethod() : defaultValue;
    myVal3 = c ? cMethod() : defaultValue;
    myVal4 = d ? dMethod() : defaultValue;

The ternary operator can only be used if you're assigning a value. Otherwise you'll have to use if statements as normal.

Thanks for the help guys. The if method is much more sound than using a switch/case, that's for sure :)

This article has been dead for over six months. Start a new discussion instead.