C# build the if conditions at runtime

1k views Asked by At

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?

2

There are 2 answers

1
Oren On BEST ANSWER

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 :)

1
Jack On
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");
                }

        }

    }