Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
ColinBurke Avatar asked Feb 14 '26 04:02

ColinBurke


2 Answers

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();
}
like image 82
Pierre-Luc Pineault Avatar answered Feb 15 '26 16:02

Pierre-Luc Pineault


Rather than encapsulate some complex condition in a method that you will only ever call once or twice, I would just keep in a variable. This is also more readable than using some marker boolean as other answers suggest.

A contrived example,

bool isBlue = sky.Color == Colors.Blue;
bool containsOxygen = sky.Atoms.Contains("oxygen") && sky.Bonds.Type == Bond.Double;
bool canRain = sky.Abilities.Contains("rain");
if(isBlue)
{
}
if(containsOxygen)
{
}
if(canRain)
{
}
if(!isBlue && !containsOxygen && !canRain)
{
}

Now we have abstracted what might otherwise be complex conditions into readable English!

like image 36
MgSam Avatar answered Feb 15 '26 18:02

MgSam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!