Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
KaptajnKold Avatar asked Aug 18 '11 07:08

KaptajnKold


2 Answers

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);
like image 196
Gabe Avatar answered Oct 21 '22 03:10

Gabe


Write a seperate method to get the phone number, something like this:

public string GetDefaultPhone(User user)
        {
            if(user == null)
            {
                return string.Empty;
            }

            if(!string.IsNullOrEmpty(user.PhoneDay))
            {
                return user.PhoneDay;
            }

            if(!string.IsNullOrEmpty(user.PhoneEvening))
            {
                return user.PhoneEvening;
            }

            if(!string.IsNullOrEmpty(user.Mobile))
            {
                return user.Mobile;
            }

            return string.Empty;
        }

And then in your code:

_viewModel.PhoneDefault = GetDefaultPhone(user);
like image 36
Jason Evans Avatar answered Oct 21 '22 05:10

Jason Evans