Hector
Hector

Reputation: 21

Simplify multiple If-Else statement

I am wondering if there is any way to simplify the following if-self code:

if(a == null)
{
  variant = 1;
} else if (a == b)
{
  variant = 5;
} else if (a == c && a != d)
{
  variant = 6
} else if ....

I ready don't want to use too much if else in my code but variant needs to be assigned to a different value depends on a.

Thanks.

Upvotes: 0

Views: 833

Answers (3)

Amo Robb
Amo Robb

Reputation: 850

I might be criticized, but if you change a little bit the appearance of your code maybe it doesn't look too "long".

   if(a == null) variant = 1;
   else if (a == b) variant = 5;
   else if (a == c && a != d) variant = 6;
   else if ....

And you don't get your code more difficult to read. Even pwilcox version (which is very nice, btw), is more complicated to read than a simple if-else.

Upvotes: 1

pwilcox
pwilcox

Reputation: 5753

In these situations I prefer chained ternary operations:

variant = 
      a == null ? 1
    : a == b ? 5
    : a == c && a != d ? 6
    : variant; // or whatever final default value you want

Upvotes: 3

Heinzi
Heinzi

Reputation: 172200

There's nothing inherently wrong with a long sequence of if - else if statements.

Since you asked for an alternative: If you extract that code into a separate method, you can use return statements and regular ifs instead. It also gets rid of the redundant variant = ... assignment, documents your code and keeps your methods short.

int DetermineVariant(int? a, int b, int c, int d)
{
    if (a == null)
        return 1;

    if (a == b)
        return 5;

    if (a == c && a != d)
        return 6;

    // more conditions
}

Upvotes: 2

Related Questions