// 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.
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.
Related
I am not able to understand the question and output here. I am well aware of the basic syntax of the ternary operator.
condition? statement 1: statement 2
if the condition is true then statement 1 otherwise statement 2.
But what's the condition in the problem given below? (true ? x : 0) What is the program checking to be true?
using System;
public class Program
{
public static void Main(string[] args)
{
char x = 'A';
int i = 0;
Console.WriteLine (true ? x : 0); //Output: 65
Console.WriteLine(false ? i : x); //Output: 65
}
}
I think this code isn't really checking something. The 'true' and 'false' are used to override the condition and execute the respective conditions.
Console.WriteLine (true ? x : 0)
This straightaway executes the first statement. Had there been false here, statement 2 would be executed. Same goes for the other one.
I want to get result of a value with if condition.
i have get some value in xml file.
now what I want is
if I have a variable "a" here i have assigned some values by using dataset.
and i have another variable "b" is assigned value from xml file.
for example
int a=25;
string b=">10"
now I want to check the condition if condition with out ">" because the symbol present in b variable. I dont know how to check this condition can anybody explain me how to acheive this.
I tried like this but not working
if(a+b)
You can use the DataTable.Compute-"trick" to evaulate such expressions:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
What is supported you can read at the DataColumn.Expression remarks.
if the condition is 1!=10, how to use not equal in this code .this
condition is not working what should i do.
As the documentation tells you that is not valid syntax, you have to use <> (look at operators). So a simple approach would be either to use <> in the first place or replace them:
b = b.Replace("!=", "<>");
You can have some function to remove non numeric characters:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
If its always a number with a symbol then:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
And considering your comment for comparison you can do:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
Of course you may need only one of < = > or you may need to have separate if conditions for each, what ever suits your needs, but I just wanted to give the idea.
I tried like this
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
similarly all the symbols
First separate symbol from b:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
Now use switch to get operation for symbol and compare:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
EDIT: Changed symbol declaration to avoid error: "cannot implicit convert type char to string"
I am trying to understand what is happening in this variable assignment.
num = forward.Data.Key >= key ? 1 : 0;
In particular this part >= key ? 1 : 0
To help out forward is a LinkedListCell<KeyValuePair<int, double>> forward = _data.Next;
key is an int parameter being passed into the method.
Also it is a program written in C#
That's the ternary operator. It takes a boolean expression, and returns one of two values depending on the result of that expression. You get it in a number of languages.
It's equivalent to:
if( forward.Data.Key >= key ) {
num = 1;
}
else {
num = 0;
}
It is called ternary conditional operator. (or the short If-Else statement)
value = condition ? truePart : falsePart;
The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison.
from MSDN,
int input = Convert.ToInt32(Console.ReadLine());
string classify;
// if-else construction.
if (input < 0)
classify = "negative";
else
classify = "positive";
// ?: conditional operator.
classify = (input < 0) ? "negative" : "positive";
We get into unnecessary coding arguments at my work all-the-time. Today I asked if conditional AND (&&) or OR (||) had higher precedence. One of my coworkers insisted that they had the same precedence, I had doubts, so I looked it up.
According to MSDN AND (&&) has higher precedence than OR (||). But, can you prove it to a skeptical coworker?
http://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx
bool result = false || true && false; // --> false
// is the same result as
bool result = (false || true) && false; // --> false
// even though I know that the first statement is evaluated as
bool result = false || (true && false); // --> false
So my question is how do you prove with code that AND (&&) has a higher precedence that OR (||)? If your answer is it doesn't matter, then why is it built that way in the language?
Change the first false by true. I know it seems stupid to have (true || true) but it proves your point.
bool result = true || true && false; // --> true
result = (true || true) && false; // --> false
result = true || (true && false); // --> true
If you really want to freak him out try:
bool result = True() | False() && False();
Console.WriteLine("-----");
Console.WriteLine(result);
static bool True()
{
Console.WriteLine(true);
return true;
}
static bool False()
{
Console.WriteLine(false);
return false;
}
This will print:
True
False
False
-----
False
Edit:
In response to the comment:
In C#, | is a logical operator that performs the same boolean logic as ||, but does not short-circuit. Also in C#, the | operator has a higher precedence than both || and &&.
By printing out the values, you can see that if I used the typical || operator, only the first True would be printed - followed by the result of the expression which would have been True also.
But because of the higher precedence of |, the true | false is evaluated first (resulting in true) and then that result is &&ed with false to yield false.
I wasn't trying to show the order of evaluation, just the fact that the right half of the | was evaluated period when it normally wouldn't be :)
Wouldn't this get you what you're after? Or maybe I'm missing something...
bool result = true || false && false;
You don't prove it with code but with logic. AND is boolean multiplication whereas OR is boolean addition. Now which one has higher precedence?
false || true && true
Yields: true
false && true || true
Yields: true
You cannot just show the end result when your boolean expressions are being short-circuited. Here's a snippet that settles your case.
It relies on implementing & and | operators used by && and ||, as stated in MSDN 7.11 Conditional logical operators
public static void Test()
{
B t = new B(true);
B f = new B(false);
B result = f || t && f;
Console.WriteLine("-----");
Console.WriteLine(result);
}
public class B {
bool val;
public B(bool val) { this.val = val; }
public static bool operator true(B b) { return b.val; }
public static bool operator false(B b) { return !b.val; }
public static B operator &(B lhs, B rhs) {
Console.WriteLine(lhs.ToString() + " & " + rhs.ToString());
return new B(lhs.val & rhs.val);
}
public static B operator |(B lhs, B rhs) {
Console.WriteLine(lhs.ToString() + " | " + rhs.ToString());
return new B(lhs.val | rhs.val);
}
public override string ToString() {
return val.ToString();
}
}
The output should show that && is evaluated first before ||.
True & False
False | False
-----
False
For extra fun, try it with result = t || t && f and see what happens with short-circuiting.
Please demonstrate how the ternary operator works with a regular if/else block. Example:
Boolean isValueBig = value > 100 ? true : false;
Exact Duplicate: How do I use the ternary operator?
Boolean isValueBig = ( value > 100 ) ? true : false;
Boolean isValueBig;
if( value > 100 ) {
isValueBig = true;
} else {
isValueBig = false;
}
The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.
To use your example, changing from the use of a ternary expression to if/else you could use this statement:
Boolean isValueBig = null;
if(value > 100)
{
isValueBig = true
}
else
{
isValueBig = false;
}
In this case, though, your statement is equivalent to this:
Boolean isValueBig = (value > 100);
When I was new to C++, I found that it helped to read this construct as follows:
Boolean isValueBig = if condition ? then x else: y;
(Notice that this isn't valid code. It's just what I trained myself to read in my head.)
Boolean isValueBig;
if (value > 100)
{
isValueBig = true;
}
else
{
isValueBig = false;
}
I was never a fan of the ternary operator because I thought it was hard to read. As it so happens, Jon Skeet and his book, C# in Depth finally hit this old dog over the head and got it to sink in. Jon said, and I paraphrase, think of it as a question.
value > 100?
"yes" : "no"
Now the blind can see.
Hope this helps you make it second nature.
Boolean isValueBig;
if(value > 100) { isValueBig = true; } else { isValueBig = false; }
As quoted from the ?: Operator MSDN page, "the conditional operator (?:) returns one of two values depending on the value of a Boolean expression."
So you can use the ternary operator to return more than just booleans:
string result = (value > 100 ) ? "value is big" : "value is small";
PHP Example
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
"The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE."
PHP Documentation on Comparison Operators
Make sure you don't mix types in true/false parts in Java. It produces weird results :-(
Bad example, because you could easily write
Boolean isValueBig = value > 100 ? true : false;
as:
bool isValueBig = value > 100
Beyond that, everyone else has already answered it. I would just not recommend using ternary operators to set bool values, since what you are evaluating is already a boolean value.
I realize it was just an example, but it was worth pointing out.
Others have answered it already but here's one thing you should really know about ternary's usage and by that I mean don't ever do it.
Lets assume that you have a piece of code which is supposed to return a different object for each possible variation of some value, lets say for simpliticy's sake an integer between 1 and 5. Your code looks like this:
if(i==1) {
return new ObjectOne();
} else if(i==2) {
return new ObjectTwo();
} else if(i==3) {
return new ObjectThree();
} else if(i==4) {
return new ObjectFour();
} else if(i==5) {
return new ObjectFive();
} else {
return new DefaultObject();
}
It's easy to understand but a bit heavy. Since ternary is just another way of writing an if..else statement that can be refactored to this
return (i==1) ? new ObjectOne() :
(i==2) ? new ObjectTwo() :
(i==3) ? new ObjectThree() :
(i==4) ? new ObjectFour() :
(i==5) ? new ObjectFive() : new DefaultObject();
It's called nested ternary. It's evil, now that you know about it please never use it. It may seem to have its uses like the case above but it's very likely that in real life situations you would need to use it somewhere where it loses readability (think altering configurations with variable amount of parameters and such).
Bonus sector: Never set attribute values inside if(), just look at this: if(bool=true!=false) { .. }
As quoted from MSDN (noted in a previous post)
string result = (value > 100 ) ? "value is big" : "value is small";
Could be read as:
Is value greater than 100? If yes, string result is "value is big", if no, string result is "value is small".