Confused about? operator in c #

I want to make sure that if the subs value is not equal to ", then UL go before and after it and to the sL variable. If subs is" ", then sL will get the value" "

var sL = (subs != "") ? "<ul>" + subs + "</ul>" : ""; 

But that does not work.

Is my format correct?

+6
source share
6 answers

If in doubt, add additional brackets:

 var sL = subs != "" ? ("<ul>" + subs + "</ul>") : ""; 

However, your code should work fine; this syntax is beautiful.

+11
source

Susan, your code is correct and it works. I just tested in LinqPad. Perhaps your ss variable is null, not empty. I recommend you change your line to:

 var sL = !string.IsNullOrEmply(subs) ? "<ul>" + subs + "</ul>" : ""; 
+4
source

It should be the same:

 if (subs != "") { sL = "<ul>" + subs + "</ul>"; } else { sL = ""; } 

If this is what you are aiming for, then I would surround "<ul>" + subs + "</ul>" in brackets, just to make sure that the compiler understands what you want.

+3
source

I copied pasta'd your code and it worked perfectly on my machine.

Perhaps the problem is elsewhere?

Aside, rather use string.IsNullOrEmpty over = ""

 var sL = !string.IsNullOrEmpty(subs) ? "<ul>" + subs + "</ul>" : string.Empty; 
+2
source

Another option that no one has mentioned is to use string.Concat instead of + , for example:

 var sL = (subs != "") ? string.Concat("<ul>", subs, "</ul>") : ""; 
+1
source

If subs is ", then sL also becomes". "You just use the shortened version of if. What you wrote is exactly the same as

 string sL; if (subs != ""){ sL = "<ul>" + subs + "</ul>"; }else{ sL = ""; } 
0
source

Source: https://habr.com/ru/post/896481/


All Articles