Search code examples
c#optimizationif-statementnested-statement

C# build the if conditions at runtime


I have nested if else structure, more or less doing the same thing.

simply it's a single if(A && B && C) but I have flag D and E for condition A and C respectively.

That means if D is false, A should be disappear and not evaluated. It's same for C not be evaluated if E if false.

Now, my code now is similar as follows:

if (D){
 if (A && B){
    if (E){
       if (C)
         { Do Something }
    } else { Do Something else}
  }
} else
  if (B) {
     if (E){
       if (C)
         { Do Something }
    } else { Do Something else}
  }
}

Is any easy way to reduce this complicated structure to several lines of code?


Solution

  • Since both branch actions are the same you could essentially write:

            if ((D && A && B) || (!D && B))
            {
                if (E && C)
                {
                    DoSomething();
                }
                else
                {
                    DoSomethingElse();
                }
            }
    

    Hopefully your variables are more readable than A,B,C etc :)