Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about the ? operator in c#

Tags:

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?

like image 512
Susan Avatar asked Sep 02 '11 11:09

Susan


People also ask

What is== operator called?

Relational Operators == (Equal to)– This operator is used to check if both operands are equal. !=

What is&& means in c?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 .

What is an operator explain their types?

In computer science, an operator is a character or characters that determine the action that is to be performed or considered. There are three types of operator that programmers use: arithmetic operators. relational operators. logical operators.

What is operator explain with example?

In mathematics and computer programming, an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.


2 Answers

When in doubt, add more brackets:

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

However, your code should work fine already; that syntax is fine.

like image 129
Marc Gravell Avatar answered Sep 28 '22 15:09

Marc Gravell


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>" : "";
like image 29
Icarus Avatar answered Sep 28 '22 17:09

Icarus