Confused about the ? operator in c#
I want to make it so that if the value of subs is not "" then the ULs go before and after it and into the variable sL. If subs is "" then sL get the value ""
var sL = (subs != "") ? "<ul>" + subs + "</ul>" : "";
开发者_如何转开发But it doesn't seem to work.
Is my format correct?
When in doubt, add more brackets:
var sL = subs != "" ? ("<ul>" + subs + "</ul>") : "";
However, your code should work fine already; that syntax is fine.
Susan, your code is correct and it works. I just tested in LinqPad. Perhaps your ss variable is null and not empty. I recommend you change your line to:
var sL = !string.IsNullOrEmply(subs) ? "<ul>" + subs + "</ul>" : "";
This should be the same to this:
if (subs != "")
{
sL = "<ul>" + subs + "</ul>";
}
else
{
sL = "";
}
If this is what you are aiming for, then I would surround the "<ul>" + subs + "</ul>"
in brackets, just to be sure the compiler understands what you want.
I copy-pasta'd your code and it worked fine on my machine.
Perhaps the problem is somewhere else?
As an aside, rather use string.IsNullOrEmpty
over = ""
var sL = !string.IsNullOrEmpty(subs) ? "<ul>" + subs + "</ul>" : string.Empty;
Another option nobody mentioned yet would be to use string.Concat
instead of +
, like this:
var sL = (subs != "") ? string.Concat("<ul>", subs, "</ul>") : "";
If subs is "" then sL becomes "" as well. You are just using a shorthand variant of if. What you have written is exactly the same as
string sL;
if (subs != ""){
sL = "<ul>" + subs + "</ul>";
}else{
sL = "";
}
精彩评论