You get hooked in C#: how can I write this in less code? How can I be more economical?
I've used the ?: conditional operator occasionally over the last couple of years, but didn't take the time to “get it.“
In short, it provides a one-time statement to replace an if(){} else {} sequence, like so:
txtWork_phone.Text = ue.work_phone != string.Empty ? TextUtils.PrettyPhone(ue.work_phone) : string.Empty;
instead of
if (ue.work_phone != string.Empty)
{
txtWork_phone.Text = TextUtils.PrettyPhone(ue.work_phone);
}
else
{
txtWork_phone.Text = string.Empty;
}
A mistaken approach to using the Conditional Operator would be something like
i < j ? i++ : j++;
This produces the error: Only assignment, call, increment, decrement, and new expressions can be
used as a statement.
k = i < j ? i++ : j++;
The trick is in utilizing the initial assignment. Cool C# tidbit for the day. Big thanks to a newsgroup post authored by Jacob Yang helping me to happily get it.