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.
>Solution :
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.