Search code examples
c#switch-statementboolean

C# switch clause on boolean variable


I have a piece of code, that is checking if a boolean variable is true and based on the condition, I perform operations accordingly:

bool result = true;
bool isTrue = false;
CheckIsTrue(ref isTrue);

if (result)
{
   if (isTrue)
   //Perform action
}

I have a need to perform another operation, if the variable is set to false:

 if (result)
 {
    if (isTrue)
    {
      //Perform action
    } 
    else if(actionType == 6)
    {
      //Perform action, isTrue = false.
    }
 }

For readability and maintainability reason, I decided to change the above to:

 if (result)
 {
     switch (isTrue)
     {
       case true:
               //perform action on isTrue
           break;
              default:
                   switch (actionType)
                   {
                      case 6:
                         //Perform action on 6
                       break;
                          default:
                        //Perform default action        
                       break;
                   }
            break;
     } 
}

My question is: is it smart to use swicth.. case... on boolean variables? This is the best way I have considered to simplify my code, however I am not sure on how correct this truly is.


Solution

  • With only one level of indentation and proper variable names:

    if (!actionShouldBePerformed) // instead of result
       return;
    
    if (defaultActionShouldBePerformed) // insted of isTrue
    {
       //Perform action
       return;
    }
    
    if (actionType == ActionType.NameOfType) // instead of magic number 6
       // Perform another action   
    

    Further reading: Replace Nested Conditional with Guard Clauses