Is it possible to write following C# code in a line without if
and else
?
string res = "";
if (!string.IsNullOrEmpty(var1))
res = string.Format("{0}/{1}", var1, var2);
else
res = var2;
Is it possible to write following C# code in a line without if
and else
?
string res = "";
if (!string.IsNullOrEmpty(var1))
res = string.Format("{0}/{1}", var1, var2);
else
res = var2;
Try this,
string res = !string.IsNullOrEmpty(var1) ? string.Format("{0}/{1}", var1, var2) : var2;
Basically,
(if this statement is true (like if block's condition part)) ? (this section works) : ((else) this section works);
Hope this helps,
The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false. The syntax for the conditional operator is as follows:
condition ? consequent : alternative
So the code line you are requested is
string res = !string.IsNullOrEmpty(var1) ? string.Format("{0}/{1}", var1, var2) : var2;
Tecnically, you can hide if
within ternary operator ?:
string res = $"{(!string.IsNullOrEmpty(var1) ? $"{var1}/" : "")}{var2}";
but what for?