SkonJeet
SkonJeet

Reputation: 4905

Better alternative to many nested if statements in this context?

if (task1 != null)
    //Do something with task1
else
{
     if (task2 != null)
         //Do something with task2
     else
     {
         if (task3 != null)
             //Do something with task3
         else
         {
             if (task4 != null)
                 //Do something with task4
         }
     }
}

Is there an alternative to the above code? I'm looking for a sort of 'flatter' way of kind of switch casing on the tasks depending which is not null.

Thanks a LOT in advance for anyone that can help.

Upvotes: 1

Views: 10670

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062550

Are they all the same type? And do you want to do the same thing in each branch? If so, you could use null-coalescing:

var chosenTask = task1 ?? task2 ?? task3 ?? task4;
// do something with chosenTask

Upvotes: 13

Milan Raval
Milan Raval

Reputation: 1882

you can use conditional operator, with condition that you need some variable on left hand side

var v = task1 != null ? do something : task2 == null ? do something : task3 != null ? do something : task4 != null ? do something : null;

Upvotes: 1

increddibelly
increddibelly

Reputation: 1229

make all tasks implement an ITask with a Run() method, and add the tasks you want to run to an ICollection so you can iterate over them.

foreach (var task in TaskCollection) {
   task.Run();
}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499780

It depends if your method does anything else. If it doesn't, you can use:

if (task1 != null)
{
    // Do something with task1
    return;
}
if (task2 != null)
{
    // Do something with task2
    return;
}
if (task3 != null)
{
    // Do something with task3
    return;
}
if (task4 != null)
{
    // Do something with task4
    return;
}

(I was about to add the same point that Marc was making - if you're going to do the same thing with whichever task is first non-null, then the null-coalescing operator is indeed your friend.)

Upvotes: 4

Related Questions