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?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With