Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use && operator in switch statement based on a combined return a value?

How can I use && operator in switch case?

This is what i want to do:

private int  retValue()
{
    string x, y;
    switch (x && y)
    {
        case "abc" && "1":
            return 10;
            break;
         case "xyz" && "2":
             return 20;
            break;
    }
}

My problem is that "abc" and "1" are both of type string and the compiler gives me message that:

"operator && cannot be applied to string"

like image 234
RachitSharma Avatar asked Feb 04 '14 05:02

RachitSharma


Video Answer


2 Answers

There is no such operator in switch statements. The switch statement operates on a single variable which is a value type or a string. See:

  • http://www.dotnetperls.com/switch
  • http://msdn.microsoft.com/en-us/library/06tc147t.aspx

The real problem in your example is that both in the switch expression, and in case labels, you are applying && to strings. You cannot apply && to strings, it only works on booleans (unless you overload it and define a new function that does work on strings).

What you are trying to accomplish is probably to simultaneously check the values of two different variables with one switch. This is impossible; switch only checks one variable at a time. The solution is to use if statements or a specialized CheckStrings(string s1, string s2) method (which may or may not use if statements).


In a comment you have expressed concerns with length. Observe:

private int retValue(string x, string y)
{
    if (x == "abc" && y == "1") return 10;
    if (x == "xyz" && y == "2") return 20;
    throw new Exception("No return value defined for these two strings.")
}

Shorter, even if you discount the gains from skipping redundant break; statements and putting returns on the same line.

like image 194
Superbest Avatar answered Sep 29 '22 07:09

Superbest


Despite there is an accepted answer already...

To achieve logical AND in switch, it has to be done like this:

    switch(x + y)
    {
        case "abc1":
            return 10;
            break;
        case "xyz2":
            return 20;
            break;
    }

Which works.

For logical OR see zey answer.

like image 22
Sinatr Avatar answered Sep 29 '22 06:09

Sinatr