// 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 works?
// 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 works?
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.
(? *) 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.