Better alternative to many nested if statements in this context?

SkonJeet picture SkonJeet · Mar 15, 2012 · Viewed 8.3k times · Source
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.

Answer

Marc Gravell picture Marc Gravell · Mar 15, 2012

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