-3

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;
Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186
mrd
  • 1,985
  • 3
  • 21
  • 47
  • 1
    res = condition ? resultiftrue : resultiffalse – Pac0 Mar 05 '20 at 13:07
  • 3
    you're looking for the [ternary operator](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator) – Jonesopolis Mar 05 '20 at 13:08
  • 1
    Why do you need the code written in one line only? – dodekja Mar 05 '20 at 13:08
  • 1
    You can quickly find that by googling terms like those in the title of your question, (along with 'C#', even if the same operator exists in many languages anyway) https://idownvotedbecau.se/noresearch/ – Pac0 Mar 05 '20 at 13:09
  • string res = string.IsNullOrEmpty(var1) ? var2 : string.Format("{0}/{1}", var1, var2) ; – Zeeshan Mar 05 '20 at 13:11

3 Answers3

3

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,

Berkay
  • 3,935
  • 2
  • 16
  • 32
2

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;
elvira.genkel
  • 1,258
  • 1
  • 2
  • 11
1

Tecnically, you can hide if within ternary operator ?:

  string res = $"{(!string.IsNullOrEmpty(var1) ? $"{var1}/" : "")}{var2}";

but what for?

Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186