0

When I try to evaluate the SelectedIndex of a CheckBoxList and at bool. I receive a error on the case in my switch statement in C#. The error is Constant value '0' cannot be converted to a 'bool'. Is there a way that I can evaluate both with in a switch statement? I know I can use a if statement, but I would rather use a switch statement if I could.

Here is my code:

switch ((CBL_PO.SelectedIndex == 0) && (boolIsNotValid == true))
            {
                case 0: case true:
                    //Do Something
                    break;
            }
nate
  • 1,418
  • 5
  • 34
  • 73

3 Answers3

3

Since the only values in the switch can be true or false, drop the case 0.

Alternatively, you could better use an if:

if (CBL_PO.SelectedIndex == 0 && boolIsNotValid)
{ }
else
{ }

Since I think you might be trying to do a check on both values in the switch: not possible. This is your best option:

switch (CBL_PO.SelectedIndex)
{
    case 0:
    {
        if (boolIsNotValid)
        { }
        else
        { }

        break;
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

A switch statement can be thought of as a replacement for a stack of if/else statements. If you are doing a single comparison then use a simple if statement; switch is overkill.

if (CBL_PO.SelectedIndex == 0 && boolIsNotValid)
{
  // Do something
}
Rob Epstein
  • 1,450
  • 9
  • 11
0

If you really want to use a switch statement, then you want:

switch ((CBL_PO.SelectedIndex == 0) && (boolIsNotValid == true))
    {
        case true:
           //Do Something
           break;
        case false:
           //Do Something else
           break;
    }
Mark Nash
  • 184
  • 10
  • So I can evaluate the SelectedIndex == 0 as the case being false? Never thought of that. I am going to try that now. – nate Aug 05 '14 at 13:02
  • I can't change the case to false, if I do, I can't evaluate with checkbox will be checked in the list. – nate Aug 05 '14 at 13:10