Search code examples
c#refactoringternary-operator

Nested ternary operators


I have this code:

_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" : 
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);

Is there a better way to write this to make it more readable?


Solution

  • In your case you can write a helper function, like this:

    // return the first parameter that isn't null or empty
    public static string CoalesceStrings(params string[] src)
    {
        foreach (var str in src)
            if (!string.IsNullOrEmpty(str))
                return str;
        return "";
    }
    

    Then just call it, like this:

    _viewModel.PhoneDefault = user == null ? "" :
        CoalesceStrings(user.PhoneDay, user.PhoneEvening, user.Mobile);