Home > database >  C# Handling Else Condition Within Nested Ifs
C# Handling Else Condition Within Nested Ifs

Time:01-31

I need to execute an else statement from a if, and another if inside it.

if (!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) //Scenario 1
{
    if (BoxA == BoxB && BoxC == BoxD) //Scenario 2
    {
        //Do something
    }
}
else
{
    // Do something else if 
    // 1) Scenario 1 hits but not scenario 2
    // 2) Scenario 1 does not hit
}

May I know how can I go to else statement regardless if scenario 1 or scenario 2 hits?

Edit: Apologies on scenario confusion. Have edited as above in else statement


At the end I went with the following solution of

if ((!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) && (BoxA == BoxB && BoxC == BoxD))
{
    //do something
}

Reason is because during if, it will hit 2nd comparison check if 1st null check fails. The purpose of my 1st null check is to prevent null exception during 2nd comparison check.

CodePudding user response:

Store the conditions in boolean variables. Then you can reuse them.

bool nullCondition = !BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull;
bool equalityCondition = BoxA == BoxB && BoxC == BoxD;

if (nullCondition && equalityCondition) 
{
  // Both conditions are true
}
else 
{
  // Any of equalitycondition or nullcondition is false
}

CodePudding user response:

You could store the scenarios in two boolean variables, which makes the check more easily:

bool scenario1 = !BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull;
bool scenario2 = BoxA == BoxB && BoxC == BoxD
if (scenario1)
{
    if (scenario2)
    {
        //do something
    }
}
if((scenario1 && !scenario2) || !scenario1)
{
    //do something else if either Scenario 1 or 2 hits.
}

Depending on what you are doing exactly, you could also give the variables more expressive names.

CodePudding user response:

I'm not sure I'm understanding you question correctly; the logic you seem to want with your example is pretty simple:

if (!BoxA_IsNull && !BoxB_IsNull && !BoxC_IsNull && !BoxD_IsNull) 
{
    if (BoxA == BoxB && BoxC == BoxD)
    {
        //Scenario 1 & 2
    }
    else
    {
        //Scenario 1 hits but not scenario 2
    }
}
else
{
     //Scenario 1 does not hit
}
  • Related