-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; 
5
  • 1
    res = condition ? resultiftrue : resultiffalse Commented Mar 5, 2020 at 13:07
  • 3
    you're looking for the ternary operator Commented Mar 5, 2020 at 13:08
  • 1
    Why do you need the code written in one line only? Commented Mar 5, 2020 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) idownvotedbecau.se/noresearch Commented Mar 5, 2020 at 13:09
  • string res = string.IsNullOrEmpty(var1) ? var2 : string.Format("{0}/{1}", var1, var2) ; Commented Mar 5, 2020 at 13:11

3 Answers 3

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,

Sign up to request clarification or add additional context in comments.

2 Comments

As OP does not know what the ternary operator is, perhaps it would be prudent to include an explanation in this answer?
You are right, tried to explain basically. @Martin
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; 

2 Comments

As OP clearly does not know what the ternary operator is, perhaps it would be prudent to include an explanation in this answer?
Added explanation, thanks
1

Tecnically, you can hide if within ternary operator ?:

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

but what for?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.