Search code examples
c#booleanswitch-statementsyntax-errorcase-statement

Constant value cannot be converted to a 'bool' using a switch statement C#


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;
            }

Solution

  • 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;
        }
    }