Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to use && or || in switch statement? Visual C#

So I was making a Rock Paper Scissor game and I've sort of made adjustments to it to include life and other things. Now I got stuck with the switch statement. My if statement works fine:

private void Result_TextChanged(object sender, EventArgs e)
{
     if (playerscore == 1 || pcscore == 1)
     {
          PlayerLife.Image = Properties.Resources.Five;
     }
}

I was wondering how I could translate this to the switch statement?

private void Result_TextChanged(object sender, EventArgs e)
{              
    switch (playerscore || pcscore)
    {
         case 1:
             PlayerLife.Image = Properties.Resources.Five;
             break;
    }
}

Doesn't seem to work.

like image 415
user2911044 Avatar asked Oct 23 '13 16:10

user2911044


2 Answers

The simple answer is No. You cant use it like that.

Switch works with single expression.

You may check MSDN for details.

You may try like this:-

  if (playerscore == pcscore)
        {
            switch (playerscore)
            {
                case 1:
                PlayerLife.Image = Properties.Resources.Five;
                break;
            }
        }

EDIT:-

As commented by Jeppe Stig Nielsen in the comments, You can switch on any expression of a suitable type. That expression may contain ||. There can be many case labels associated with each switch section in a switch block.

But personally speaking that would not be a good practice to follow. You may try to use if statement for that.

You may try like this if you want:

 switch (playerscore == 1 || pcscore == 1)
like image 112
Rahul Tripathi Avatar answered Oct 01 '22 00:10

Rahul Tripathi


In C#, a switch statement resolves a single expression and compares that value with a list of possible cases:

switch(someExpression)
{
   case x: // This runs if someExpression == x
      break;
   case y: // This runs if someExpression == y
      break;
}

Now, you could switch on the expression (playerscore == 1 || pcscore == 1) like so:

switch(playerscore == 1 || pcscore == 1) // This expression is either true or false
{
   case true: // Runs if playerscore is 1 or pcscore is 1
      break;
   case false: // runs if neither playscore or pcscore are 1
      break;
}

However, the above is rather unreadable and silly. You'd be best off with the if statement:

if(playerscore == 1 || pcscore == 1)
{
   // Runs if playerscore is 1 or pcscore is 1
}
else
{
   // runs if neither playscore or pcscore are 1
}
like image 29
Mike Christensen Avatar answered Oct 01 '22 00:10

Mike Christensen