about the ternary operator that have ? and :

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hi!

Here I have an if clause that I have replaced with the special ternary
operor that use ? and : but
it doesn't work. Have I missed something here perhaps ?

if (index == 0)
index = myList.Count - 1;
else
index--;

index = index == 0 ? myList.Count - 1 : index--;

//Tony
 
Hi!

Here I have an if clause that I have replaced with the special ternary
operor that use ? and : but
it doesn't work. Have I missed something here perhaps ?

if (index == 0)
index = myList.Count - 1;
else
index--;

index = index == 0 ? myList.Count - 1 : index--;

//Tony

The code appears to be fine. In what way does it not work?
 
Tony said:
index = index == 0 ? myList.Count - 1 : index--;

You've hit one of the caveats of using the (postfix-)decrement (and
increment) operator. The evaluation of the statement above in case of a
non-zero (let's say 5) "index" goes like this:

* "index" = 5
* The result of "index == 0 ? myList.Count - 1 : index" is 5
* The value of "index" is decremented
* The result of the ternary operator ( *5* ) is assigned to "index"
 
Here I have an if clause that I have replaced with the special ternary
operor that use ? and : but
it doesn't work. Have I missed something here perhaps ?

if (index == 0)
index = myList.Count - 1;
else
index--;

index = index == 0 ? myList.Count - 1 : index--;

Well, I haven't tested this yet, but I'm guessing that if index != 0 you're
getting back index instead of index - 1. If that's the case, the problem is
the postfix operator. Use "index - 1" instead if "index--". If that's not
the case, then I don't know what's wrong until you tell us why "it doesn't
work."
 
Tony said:
Hi!

Here I have an if clause that I have replaced with the special ternary
operor that use ? and : but
it doesn't work. Have I missed something here perhaps ?

if (index == 0)
index = myList.Count - 1;
else
index--;

index = index == 0 ? myList.Count - 1 : index--;

It doesn't have anything to do with using the conditional operator. What
do you think the result of this would be:

int x = 5;
x = x++;

A rule of thumb is not to use the prefix or postfix operators on terms
that appear on both sides of an assignment or even more than once in an
expression. Even if you know the order of evaluation and assignment,
it's still an obscure way to write code. Besides, the prefix and postfix
operators are conveniences that let you avoid having to write

x-=1;

in addition to the expression in which you used x. If x is what you're
assigning to anyway, then you aren't saving yourself any time or typing
by using the postfix operator. Just use

index = index == 0 ? myList.Count - 1 : index - 1;
 
That's simply not the equivalent.
The equivalent is:
index = index == 0 ? myList.Count - 1 : index - 1;
 
Back
Top