jose
jose

Reputation: 2543

C# conditional statement

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

Upvotes: 0

Views: 4517

Answers (4)

Crast
Crast

Reputation: 16316

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.

Upvotes: 16

jason
jason

Reputation: 241601

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.

Upvotes: 10

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391306

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;

Upvotes: 1

Sam Doshi
Sam Doshi

Reputation: 4376

Surely an easier way is:

isFollowing = !isFollowing;

Otherwise using ?:

isFollowing = isFollowing ? false : true;

Upvotes: 1

Related Questions