What is this ternary operator condition here (true ? x : 0) - c#

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.

Related

Using conditional operator ? to avoid if condition

I have the following C# code
public Config(SConfig[] c)
{
GpsdIp = c[0].Ip;
GpsdPort = c[0].Port;
CompassIp = c[1]?.Ip;
CompassPort = c[1]?.Port;
}
CompassPort = c[1]?.Port; is giving a warning (red carpet)
Cannot implictly convert int? to int. Explict conversion exists are you missing a cast?
My intention here is that if the SConfig[] c contains one element it should be assigned to GpsdIp and GpsdPort. If it contains two elements then the second element should be treated as CompassIp and CompassPort. I would really like to avoid and if condition if I can.
What in your code is null conditional operator. Your correct syntax should be:
CompassIp = c.Length > 1 ? c[1].Ip : null;
CompassPort = c.Length > 1 ? c[1].Port : 0;
PS: You would get an Index out of range exception at runtime if it would be compilable.
Anything you do, other than an if statement, to accomplish the same will have more overhead than a simple if.
That said, it would seem ripe for a ternary.
public Config(SConfig[] c) {
GpsdIp = c[0].Ip;
GpsdPort = c[0].Port;
CompassIp = c.Length == 1 ? CompassIp : c[1].Ip;
CompassPort = c.Length == 1 ? CompassPort : c[1].Port;
}
You should learn the basics of C#. When trying to access at item outside array bounds, IndexOutOfRangeException is raised instead of returning default nullable value.
The solution for you is to use if operator:
if (c.Length > 1)
{
CompassIp = c[1].Ip;
CompassPort = c[1].Port;
}

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

assigning value to bool inside while loop

I know this is a very newbie C# question but I am implementing a small program which does the following:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
bool isRun = false;
int number = 0;
while (isRun = (true) && number < 3)
{
++number;
Console.WriteLine("Number = {0}", number.ToString());
Console.WriteLine();
}
Console.WriteLine(isRun.ToString());
Console.ReadLine();
}
}
}
At the end of the while loop, I would have expected the bool value to be true, but is is printed to be false. Why is that? Is this different from C++ where I would have done something like and the same thing in C# is giving me false
while(number<3)
{
is = true;
}
if(is){
cout<<true;
}
The reason you're seeing this behavior is due to the operator precedence involved. Here the && binds more strongly than = so the code in the loop is actually bound as the following
while (isRun = (true && number < 3)) {
...
}
Once number > 3 the && expression is false and is assigned into the isRun value and simultaneously terminates the loop. Hence once the loop exits you will see isRun as false
To get the behavior you are looking for you will need to manually correct the precedence with parens.
while ((isRun = (true)) && number < 3) {
...
}
Note: In general, as #Servey pointed out, the assignment of locals to expressions inside the loop predicate is considered bad practice. Many C# users would actually be surprised that code compiles at all because they've been conditioned to only use == in loops.
It's more idiomatic to simply set isRun to true on the first line of the loop for this pattern.
while (number < 3) {
isRun = true;
...
}
The problem is that you have set you boolean variable to false and without assigning it back to true, in while loop you are matching it against the value true, thus it fails in every case.

Does .net stop checking the rest of an IF statement if you use an and/or ( || / && )?

say you have something like:
int num = 0
then you do
if(num > 5 || num < 4)
{
...
}
it checks both, but what if you do
if(num < 4 || num > 5)
{
...
}
does it only check the 1st statement?
same as:
if(num > 5 && num == 0)
{
...
}
it should stop after failing the 1st and... right?
This is called boolean short-circuit evaluation and (although [citation-needed]) yes, C# and VB.NET have it (thanks #Lasse for the correction).
In C#, || and && are the short-circuited versions of | and &, respectively
.
Yes, this feature is called short circuit evaluation. If the first argument to the AND operator (&&) is false, then the entire expression will be false. Similarly with OR (||) if the first operand in true, the entire thing is true.
This feature is useful if you want to write the code similar to:
if(a != null && a.isValid())
... Code ...
This way you are not going to get an exception if a is null.
MSDN documentation http://msdn.microsoft.com/en-us/library/2a723cdk%28v=vs.71%29.aspx
If you do it right, yes. Take a look here: http://devpinoy.org/blogs/nocampo/archive/2007/09/28/short-circuit-evaluation-in-c-and-vb-net.aspx
EDIT: To clarify; C# yes, VB.NET if you use the right keywords.

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.

Categories

Resources