I'm not a c# programmer at all, but need to get certain calculations from a C# app. No I ran into something that I'm not sure if what the output is
I have the following line of code
pageSizeFactor = PrintingRequirements.FormSize == FormSize.A4 ? 1 : 2;
I just need to confirm if I am correct, the above means the following, pageSizeFactor = the Formsize, so if the Formsize is A4 pageSizeFactor will be 1 else it will be 2?
Yes; if PrintingRequirements.FormSize is FormSize.A4, pageSizeFactor will be 1. Otherwise, it will be 2.
That operator (?:) is known as the conditional operator. It is also sometimes known as the ternary operator. Its syntax goes like this:
a ? b : c
If a evaluates to true, the result will be b; otherwise, it will be c.
That is the conditional operator:
result = boolean-expression ? expression-if-true : expression-if-false
Essentially if - else inline.
A simple way to write the code you provided is:
if (PrintingRequirements.FormSize == FormSize.A4){
pageSizeFactor = 1;
} else {
pageSizeFactor = 2;
}
Related
I know it is possible to make it with a two line code but I was wondering if it is possibble to 1 line. I feel like I saw a usage with the ? operator but couldn't find what I am looking for.
Such as,
bool val = true;
if (a == true){
a = !val
}
edit: changed the sample code
One line
Techinically this is single line:
if (a == true) a = !val;
If a is not nullable then this works too:
if(a) a = !val;
?: operator
I think you may be looking for ?: operator:
a = a ? !val : a;
The if is better.
&= and |= operators
For the kind of logic you're doing here &= and |= operators
may be used.
&= and |= operators will give you the most concise solution but if is arguably easiest to read and see what's happening.
(a = !val) compares the a to the val and alter the value
I want to use the ternary operator to determine whether or not a variable should change.
The code looks as follows:
var c = "hello";
var appendWorld = false;
c = appendWorld ? string.Concat(c, " world") : c;
Since the value in case appendWorld is false, is the same as it was before, I was wondering if there's a more concise way of writing this code.
Please keep in mind that this is just a simplified example.
I want to be able to write something like this: c = appendWorld ? string.Concat(c, " world"); where c automatically stays the same if appendWorld is false.
Does something like this exist?
The simplest solution I think is to use an if condition
if(appendWorld)
c = string.Concat(c, " world");
QUESTION IS: If this issue is clear to you, please explain to me what im not seeing. My question is: How does ternary actually work? To clarify my question: What does right to left associativity really mean here? Why is associativity not the same as order of evaluation? It is clearly like an if else statement. It is not evaluated from right to left. It seems to me to be left to right associative.
I made booleans to try and prove this. It shows me it isnt right associative.(I might not understand what right associative means.) If it was right associative, it would work like this, which was an answer which was given to me:
"Since this operator is right-associative, your code works as;"
true ? false ? false ? false ? 3 : 4 : 5 : 6 : 7
evaluated as;
true ? false ? false ? (false ? 3 : 4) : 5 : 6 : 7
which evaluated as;
true ? false ? false ? 4 : 5 : 6 : 7
which evaluated as;
true ? false ? (false ? 4 : 5) : 6 : 7
which evaluated as;
true ? false ? 5 : 6 : 7
which evaluated as;
true ? (false ? 5 : 6) : 7
which evaluated as;
true ? 6 : 7
which returns 6.
I tried to prove this, like this:
int Proof = ternaryTrueOne() ? ternaryTrueTwo() ? ternaryFalseOne() ?
ternaryTrueThree() ? ternaryFalseTwo() ? 2 : 3 : 4 : 5 : 6 : 7;
static bool ternaryTrueOne()
{
Console.WriteLine("This is ternaryTrueOne");
return true;
}
static bool ternaryTrueTwo()
{
Console.WriteLine("This is ternaryTrueTwo");
return true;
}
static bool ternaryTrueThree()
{
Console.WriteLine("This is ternaryTrueThree");
return true;
}
static bool ternaryFalseOne()
{
Console.WriteLine("This is ternaryFalse");
return false;
}
static bool ternaryFalseTwo()
{
Console.WriteLine("This is ternaryFalseTwo");
return false;
}
In that case this would be evaluated in the same way. Right? That means ternaryfalsetwo would write first in to the console. But it doesnt. It doesnt write at all. It actually works like this, and ive written the ternary expression as an if statement. It works left to right, and it does not have to evaluate the rest of the code. All other statements are unreachable after the first false statement.
private static int Proof2()
{
if (ternaryTrueOne())
{
if (ternaryTrueTwo())
{
if (ternaryFalseOne())
{
if (ternaryTrueThree())
{
if (ternaryFalseTwo())
{
return 6;
}
else
{
return 7;
}
return 5;
}
else
{
return 6;
}
return 4;
}
else
{
return 5;
}
return 3;
}
else
{
return 4;
}
return 2;
}
else
{
return 3;
}
}
Was the original answer wrong? What does right associativity really mean?
Since the ternary conditional operator has its own place in the operator precedence table, (i.e. no other operator has exactly the same precedence as it), the associativity rule only applies when disambiguating a conditional operator from another.
Right to left associativity means that the implicit parentheses are around the rightmost ternary.
That is,
a ? b : c ? d : e
is equivalent to
a ? b : (c ? d : e).
https://en.wikipedia.org/wiki/Operator_associativity is a useful link.
Associativity and order of execution are related, but not identical.
Associativity exists regardless of any execution - it's defined in math, which is exclusively formed of pure functions, so "order of execution" has no bearing on the result.
The order of execution in a ternary operator in C# is very simple:
Evaluate condition
Evaluate trueBranch if condition is true, or falseBranch if condition is false
You can imagine associativity rules as "where do the parens belong".
Consider this:
a ? b : c ? d : e
If we don't know anything about how associativity works, we can see different ways of putting the parens:
(a ? b : c) ? d : e
a ? b : (c ? d : e)
The first approach is left-associative, the second is right-associative
It shouldn't be hard to see that the two approaches lead to different results. For example,
(true ? true : false) ? false : false // false
true ? true : (false ? false : false) // true
Now, if you rewrite this in separate if statements (which usually isn't the way a ternary is actually executed, but it will do), you'll get this:
if (a)
{
return b;
}
else
{
if (c) return d;
else return e;
}
The evaluation is the same as with the simple ternary:
Evaluate condition a
If true, evaluate and return b; otherwise continue
Evaluate condition c
If true, evaluate and return d; otherwise evaluate and return e
This should make it obvious how associativity and order of execution works. So we can finish the trip, and explain your example.
We have a series of nested conditionals:
a ? b ? c ? 0 : 1 : 2 : 3
How does associativity apply here? It doesn't. There's no associative operation here! What you're doing is:
a ? (b ? (c ? 0 : 1) : 2) : 3
There's no other way to put the parens - this is the only possible way of parsing the operators.
Since the ternary operator is, well, ternary, this is a bit hard to see, but it becomes more obvious when you rewrite it as a function (e.g. "non-inline operator"):
var f = (a, b, c) => a ? b : c;
f(a, f(b, f(c, 0, 1), 2), 3);
There's no ambiguity - there's no alternative way to parse this expression.
Showing associativity with binary operators is a bit simpler, so consider this scenario:
a - b - c
If you don't know about the associativity of -, you can see two alternative ways of putting the parens - (a - b) - c and a - (b - c), which can give you two different results. Thus, - is not associative.
Compare to +, which is ("fully") associative - (a + b) + c and a + (b + c) are exactly the same thing.
I am new to learning C# and Silverlight and have been given some application files by my employer to start learning. I am able to understand most of the logic, methods and syntax used in C# but there is one line which is very confusing to me. I dont have access to my seniors right now to ask them so the logic behind it so I thought I will ask here.
Take a look at this:
In a .xaml.cs file:
List<object> lst = new List<object>();
lst.Add(GP.mpl.A);
lst.Add(GP.mpl.B);
lst.Add(GP.mpl.C);
lst.Add(GP.mpl.StnNo);
In a different .cs file:
public int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
I understand that StnNo is being received from lst[3] and converted to Integer through
Convert.ToInt32(lst[3].ToString()
But I dont understand this part:
== string.Empty ? 0 : Convert.ToInt32(lst[3].ToString())
Could you tell me what's going on there? I have done multiple searches on google but didn't find anything related. Thanks for any help.
? is a ternary operator.
condition ? first_expression : second_expression;
?: Operator (C# Reference)
So in you example,
public int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
is equal to
public int StnNo;
if (lst[3].ToString() == string.Empty)
{
StnNo = 0;
}
else
{
StnNo = Convert.ToInt32(lst[3].ToString());
}
This is the conditional, sometimes referred to as ternary, operator.
It takes the form boolean expression ? true value : false value.
In C#, the true value and false value must be of the same type, or one must be implicitly convertible to the other (but not both). Otherwise, you must legally and explicitly cast one or both to a common type.
In your code, you have
int StnNo = Convert.ToInt32(lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()));
it is producing the functional equivalent of
int temp;
if (lst[3].ToString() == string.Empty)
temp= 0;
else
temp = Convert.ToInt32(lst[3].ToString());
int StnNo = Convert.ToInt32(temp);
You can see the outer Convert.ToInt32 in your code is actually redundant and can be eliminated.
int StnNo = lst[3].ToString() == string.Empty ? 0 : Convert.ToInt32(lst[3].ToString());
That's a very poorly written way of saying "if lst[3] is empty, then use 0, otherwise parse lst[3]" - because as your question illustrates, it's harder to tell what exactly the original developer intended.
To make it more clear, let's dissect it.
lst[3].ToString() == string.Empty means "does the lst[3] evaluate to an empty string?"
? X : Y means "if so, X, otherwise Y.
0 a constant value
Convert.ToInt32(lst[3].ToString()) parses the value as an lst[3] integer.
Finally the whole expression is passed into another Convert.ToInt32, but this is entirely unnecessary because the result of the conditional expression is always an int.
Since you don't have to call Convert.ToInt32 twice, a better way of writing this would be:
public int StnNo =
(lst[3].ToString() == string.Empty
? 0
: Convert.ToInt32(lst[3].ToString()));
An even better way of writing this would be:
int StnNo;
int.TryParse(lst[3], out StnNo);
It's more lines of code, but it's a lot easier to read.
== string.Empty ? 0 : Convert.ToInt32(lst[3].ToString()) is to check that if lst[3] does not contain any value, then 0 will be assigned to StnNo.
I was reading through someones old code and I found this line:
menuItem.Checked = (menuItem.Checked == false) ? true : false;
I dont understand what it does and how. any help?
It's a complicated way to write:
menuItem.Checked = !menuItem.Checked;
Take a look at Conditional Operator: ? :
This means:
if(menuItem.Checked == false)
{
menuItem.Checked = true;
}
else
{
menuItem.Checked = false;
}
Your statement means:
if(menuItem.Checked == false)
menuItem.Checked = true;
else
menuItem.Checked = false;
Your statement is actually doing a toggle effect on the menuItem. If it is Checked then the statement is setting it to UnChecked and vice versa
From MSDN ?: Operator (C# Reference)
The conditional operator (?:) returns one of two values depending on
the value of a Boolean expression. Following is the syntax for the
conditional operator.m
condition ? first_expression : second_expression;
This can be replaced with following code:
menuItem.Checked = !menuItem.Checked;
That's the equivalent of :
menuItem.Checked = !menuItem.Checked;
Here is the MSDN article on it. It has links to other useful operators: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx
It's called Ternary Operators and a simple Google search gives great information about how this works and possibilities.
Take a look: https://www.google.com/search?q=Ternary+Operators+c%23
As people already have pointed out, this is just a shorter and easier way to write simple if-statements.
It is called a ternary operator. It is used like an if else statement but more condensed.
Its called ternary because it takes three operands.
It evaluates the first, and then choses the second if true, third if false.