Reputation: 33
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?
Upvotes: 1
Views: 1133
Reputation: 761
I have tested it in c since I am on unix console right now. However, logical operators work the same way for c#. following code can also be used to test the equivalance.
#include<stdio.h>
void test(int,int,int,int,int);
void test1(int,int,int,int,int);
int main()
{
for(int i =0 ; i < 2 ; i++)
for(int j =0 ; j < 2 ; j++)
for(int k =0 ; k < 2 ; k++)
for(int l =0 ; l < 2 ; l++)
for(int m =0 ; m < 2 ; m++)
{
printf("A=%d,B=%d,C=%d,D=%d,E=%d",i,j,k,l,m);
test(i,j,k,l,m);
test1(i,j,k,l,m);
printf("\n");
}
return 0;
}
void test1(int A, int B, int C, int D, int E)
{
if( B && (!D || A) && (!E || C))
{
printf("\n\ttrue considering flags");
}
else
{
printf("\n\tfalse considering flags");
}
}
void test(int A, int B, int C, int D, int E)
{
if(D)
{
if( A && B)
if(E)
if(C)
{
printf("\n\ttrue considering flags");
}
else
{
printf("\n\tAB !C DE");
}
}
else
{
if( B)
if(E)
if(C)
{
printf("\n\t!D --ignore A-- BC E");
}
else
{
printf("\n\tfalse considering flags");
}
}
}
Upvotes: 0
Reputation: 3248
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 :)
Upvotes: 1