views:

249

answers:

4

I want to switch the value for isFollowing. If it's true I want isFollowing = false and the opposite too.

Instead of 'if' statement i am using ? :

        isFollowing == true ? isFollowing = false : isFollowing = true;

But this isn't working. it gives "Only assignment, call, increment, decrement, and new object expressions can be used as a statement" Why is that ?

Thanks in advance

+10  A: 

Use:

isFollowing = !isFollowing;

To make this work using the ternary operator:

isFollowing = isFollowing ? false : true;

But don't do that, just use the first version.

The reason why what you have doesn't work is because the ternary operator is of the form

conditon ? expression_if_condition_is_true : expression_if_condition_is_false;

and this evaluates to an expression (expression_if_condition_is_true if condition is true and expression_if_condition_is_false if condition is false). Expressions can not be used as statements unless they are method calls, increments (i.e., i++), decrements, allocations using new and assignments.

Jason
+15  A: 

If you wanted to keep it as a ternary, you could do

isFollowing = (isFollowing == true ? false : true);

However, this is a much shorter equivalent:

isFollowing = !isFollowing;

The reason why your code didn't work is that a ternary on its own is an expression, and not all expressions are valid statements. By converting it to an assignment to the value of a ternary, it becomes a statement.

Your code would be most likely valid in C, as long as it satisfied operator precedence rules, but C# will not allow you to do this. As a practice, it's best to limit your ternary branches to not having side effects anyway, even if the language allows you to do it.

Crast
If you're going to give a ternary version at least give a statement without redundancies: `isFollowing = isFollowing ? false : true;` The `isFollowing == true` is unnecessary.
Jason
This is true, but I was attempting to illustrate the closest working version of his code. It's obviated by the fact that a ternary is un-necessary anyway.
Crast
+1  A: 

Surely an easier way is:

isFollowing = !isFollowing;

Otherwise using ?:

isFollowing = isFollowing ? false : true;
Sam Doshi
+1  A: 

The reason you're getting the error is that you have an assignment in the middle of the expresion:

isFollowing == true ? isFollowing = false : isFollowing = true;
                                  ^
                                here

The ternary operator is an expression, and you cannot have this type of expression by itself, you need to assign it to something.

The other answers here give you the solution on how to rewrite it:

isFollowing = !isFollowing;
Lasse V. Karlsen