Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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();
}

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top