Reputation: 1428
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;
}
Upvotes: 0
Views: 2098
Reputation: 156978
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;
}
}
Upvotes: 3
Reputation: 192
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;
}
Upvotes: 0
Reputation: 1500
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
}
Upvotes: 1