How does the ternary operator work? - c#

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".

Related

In C#, what does an expression x = y == z stand for?

Please forgive me the noob question, but C# is not my native language. In code I took over, I stumbled upon
var success = true;
success = Upload.Status == FileStatus.Ok;
In there, FileStatus is of type enum, somewhere custom defined. I guess, success is essentially non-nullable Boolean. I think that the 2nd line sets success to false if (and only if) Upload.Status == FileStatus.Ok, which would also induce that the latter two variables should be of same type.
Could you please let me know, whether my hypotheses are correct? Also: How is such a construct called? What is it short for?
success is going to be a bool.
It is initialized with true, but that should be unessesary.
var success = true;
And will then be set to the result of (Upload.Status == FileStatus.Ok) which is a bool.
success = Upload.Status == FileStatus.Ok;
Think of it as success = (Upload.Status == FileStatus.Ok); if that helps.
And yes, it took me a moment to parse it too. I have a profound dislike for people trying to save lines at the cost of readability. I would use this:
if(Upload.Status == FileStatus.Ok)
success = true;
else
success = false;
Maybe use the shorter if syntax.
Upload.Status == FileStatus.Ok evaluates to a bool, either true or false. success will be assigned the result of that evaluation.
It's no more mystical than var sum = 4 + 5; resulting in sum being assigned a value of 9.
It's assigning the result of an expression to a variable, same as var x = 1 + 2; just that in this case the expression is of type bool.
Needlessly verbose, this would be the same:
bool success;
if (Upload.Status == FileStatus.Ok)
{
success = true;
}
else
{
success = false;
}

I am trying to understand what is happening in this variable assignment

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";

c# Can someone explain this boolean logic

// 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.

Using return and short-hand if in C#

Why wouldn't the following line of code work in a method?
return (count > 0) ? true : false;
It works perfectly fine if I do:
bool ret = (count > 0) ? true : false;
return ret;
Bonus Question: Is it really faster or more effective than the standard if statement?
bool ret = false;
if(count > 0)
ret = true;
return ret;
Which one would you recommend?
I would recommend:
return count > 0;
There's no need to explicitly return true or false.
Having said that, your compilation error intrigues me. At first sight it looks like it should work. Could you post a short but complete example that fails to compile? The type of that conditional expression should be bool with no problems. My guess is you've got a more complicated scenario, and by simplifying the example you've removed the real problem.
As for the bonus question: I don't know which would be faster, nor do I care in 99.99% of cases. I'd be amazed to find that it caused any significant delay, unless it prohibited inlining for some reason. Go for the most readable solution - which is the simple return statement, IMO.
try this:
return count > 0;
before return returns the expression count > 0 is evaluated and gives true or false.
this should also work:
return (count > 0 ? true : false);
but I'd recommend you didn't do this.
I always try to keep the amount of horizontal operations low, I believe it makes it easier to read code.
just imagine the following scenario which will just confuse :)
return count > 0 ? false : true;
From the point of view of C#
return count > 0;
is better for it's readabilty.
But the compiler optmize the code, so your three options are actually the same once compiled. You could try to look at the IL code to verify!
this works
return (count > 0 ? true : false);
You can then make it return other values than true and false. In your particular case I would do like the other suggestions; return count > 0;

What does this snippet of C# code do?

What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;

Categories

Resources