Search code examples
c#if-statementlogicconditional-statements

Using one else with multiple if statements in C#


Is there a way to quickly check the following logic in C#?

if (a)
{

}
if (b)
{

}
if (c)
{

}
else //none of the above, execute if all above conditions are false
{
  /* do something only if !a && !b && !c  */
}

This differs from using if-else in that a, b, and c can all be true at once, so I can't stack them that way.

I want to run the else block when a, b, and c are all false without writing if (!a && !b && !c). This is because the code can get quite messy when the if conditions become more complex. It requires rewriting a lot of code.

Is this possible?


Solution

  • Firstly, no, else blocks only respect the if clause immediately above them, so you'll need an alternative.

    This option isn't especially "clean", but I'd do:

    bool noneAreTrue = true;
    if(a)
    {
        noneAreTrue = false;
    }
    if(b)
    {
        noneAreTrue = false;
    }
    if(c)
    {
        noneAreTrue = false;
    }
    if(noneAreTrue)
    {
        //execute if all above conditions are false
    }
    

    Also, if your conditions are really pretty big, I recommend the rule G28 (Encapsulate Conditionals) from the book Clean Code from Robert C. Martin.

    It is pretty verbose, but can be easier to read in some instances:

    public void YourMethod()
    {
        if(SomeComplexLogic())
        {
        }
        if(SomeMoreLogic())
        {
        }
        if(EvenMoreComplexLogic())
        {
        }
        if(NoComplexLogicApply())
        {
        }
    }
    
    private bool SomeComplexLogic(){
        return stuff;
    }
    
    private bool EvenMoreComplexLogic(){
        return moreStuff;
    }
    
    private bool EvenMoreComplexLogic(){
        return evenMoreStuff;
    }
    
    private bool NoComplexLogicApply(){
        return SomeComplexLogic() && EvenMoreComplexLogic() && EvenMoreComplexLogic();
    }