开发者

c# Can someone explain this boolean logic

开发者 https://www.devze.com 2023-01-15 16:26 出处:网络
// Example bool is true bool t = true; // Convert bool to int int i = t ? 1 : 0; Console.WriteLine(i); // 1
// Example bool is true
bool t = true;

// Convert bool to int
int i = t ? 1 : 0;
Console.WriteLine(i); // 1

This converts false to 0 and true to 1, can someone explain to me how the t ? 1 : 0 work开发者_如何转开发s?


Look at the Ternary Operator.

int i = t ? 1 : 0;

Equates to:

if(t)
{
    i = 1;
}
else
{
    i = 0;
}

This syntax can be found in a variety of languages, even javascript.

Think of it like an English sentence if you swap the colon for "otherwise":

bool isItRaining = false;
int layersOfClothing = isItRaining? 2 otherwise 1;


It's the C# Conditional Operator.

i = does t == true? if yes, then assign 1, otherwise assign 0.

Can also be written as:

if (t == true)
   t = 1;
else 
   t = 0;

or

if (t)
  t = 1;
else
  t = 0;

Since t is true, it prints 1.


if t equels true then i=1 else i=0

ternary operator


bool t= true;
int i;

if(t) 
{
 i=1;
}
else
{
 i=0;
}

For more look ?: Operator


(? *) this is conditional operator.

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form

condition ? first_expression : second_expression;

here in you case (true?1:0 ) since the condition is true ,which is certainly setting value of i to 1.


I believe that internally the compiler will inline the statement to the equivalent of:

Console.WriteLine(Convert.ToInt32(t));

This Convert.x method checks to see if the passed parameter is true return 0 if it isn't.

0

精彩评论

暂无评论...
验证码 换一张
取 消