How to use ternary operator for this statement in

2019-01-26 06:33发布

int five = 5;
  • when the variable five is equal to 5, write true
  • when the variable five is not equal to 5, write false

How do I write a statement for this in ASP.NET using C#?

11条回答
唯我独甜
2楼-- · 2019-01-26 06:58
int five = 5;
string answer = five == 5 ? "true" : "false";

I see that you want to use this to write the values out in ASP.NET, the answer string will hold your desired value, use that as you please.

查看更多
相关推荐>>
3楼-- · 2019-01-26 07:01

The ternary operator in just about every language works as an inline if statement:

Console.WriteLine((five == 5) ? 'true' : 'false');

(You shouldn't strictly need the inner parens, but I like to include them for clarity.)

If the boolean evaluates to true, then the entire expression is equal to the value between the ? and :. If the boolean evaluates to false, the expression equals the value after the :.

I don't believe you can include lines of code in the middle of the operator. These are simply supposed to be expressions that replace the entire operator "phrase" once the condition is evaluated.

I'm a Java guy and don't really know C#; maybe it's different. But probably not.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-26 07:09

In ASP.NET, declarative (i.e, where the HTML goes):

<p>Is this five? <%= yourVariable == 5 ? "true" : "false"; %></p>

Or, alternatively, in code behind (i.e., where your C# code and classes are):

someTextBox.Text = yourVariable == 5 ? "true" : "false";
查看更多
ら.Afraid
5楼-- · 2019-01-26 07:09

Simplest thing is Console.WriteLine((five == 5).ToString());

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-26 07:11

From @JohnK's comment use:

int five = 5;
string answer = five == 5 ? bool.TrueString : bool.FalseString;

Represents the Boolean value true/false as a string. This field is read-only. https://msdn.microsoft.com/en-us/library/system.boolean.truestring(v=vs.110).aspx

查看更多
Juvenile、少年°
7楼-- · 2019-01-26 07:16

Yet another variation:

string message = XmlConvert.ToString(5 == five);
Console.Write(message);
查看更多
登录 后发表回答