Home > Back-end >  multiple conditions with if else
multiple conditions with if else

Time:12-29

var car = repository.Get(id);
if(car != null)
{
  if(car.AdditionalInfo != null)
  {
     if(car.AdditionalInfo.CarOwner.Status == "USA")
     {
        ...
     }
     else
     {
       .. do something for
     }
  }
  else
  {
     // create additional info and save
  }
}
else
{

}

Having following situation in mind with multiple if conditions, is there some cleaner way to write this? Don't focus on the Status property, rather to the flow of if else.

CodePudding user response:

You can use the null conditional operator ?.

if (car?.AdditionalInfo?.CarOwner?.Status == "USA")
{
...
}

If car, or AdditionalInfo, or CarOwner are null, then everything on the left will resolve to null, otherwise you will get the status, and then you can make your comparison.

CodePudding user response:

You can use the ? operator:

var car = repository.Get(id);
if(car?.AdditionalInfo?.CarOwner?.Status == "USA" != null)
{
  
}
else
{

}

CodePudding user response:

I think it would be best to reduce nesting by inverting ifs and introducing a function. Null coalescing operator is obfuscating readability when there are several conditions. I would go with something alike, because here you only consider one condition at time:

public void HandleCar()
    {
        var car = repository.Get(id);
        
        if (car is null)
            return;

        if (car.AdditionalInfo is null)
        {
            // create additional info and save
            return;
        }

        if (car.AdditionalInfo.CarOwner.Status == "USA")
        {
            // ...
            return;
        }

        // .. do something for
    }
   
  • Related