Ryan R
Ryan R

Reputation: 8461

Difference between if statement ways...?

I am trying to use the shorthand notation for an if statement to shorten the following:

if (DCC.systemFlags[1]) { sf0CheckBox.Checked = true; } else { sf0CheckBox.Checked = false; }

And to use the following instead:

DCC.systemFlags[1] ? sf1CheckBox.Checked = true : sf1CheckBox.Checked = false;

However, I am not sure why I am getting the following error:

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

What is the correct way to write this?

DCC.systemFlags[] is an array of bools.

Thank you.

Upvotes: 0

Views: 303

Answers (5)

StriplingWarrior
StriplingWarrior

Reputation: 156459

What you really want in this case is:

sf1CheckBox.Checked = DCC.systemFlags[1];

But if you really wanted to use the ternary operator, this would be the way to do it:

sf1CheckBox.Checked = DCC.systemFlags[1] ? true : false;

The problem is that the ternary operator uses the following syntax:

[condition] ? [expression] : [expression]

[expression]s must evaluate to some value (e.g. 5 + 1), and cannot be statements (e.g. a = 5 + 1).

Upvotes: 3

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

A ternary operator statement

a = b ? foo : bar;

directly translates to

if (b) { a = foo; } else { b = bar; }

You're getting that error because all you have is the latter part of your expression (i.e. the b ? foo : bar part). You're not using that snippet of code anywhere. It's not assigning anything, calling anything, incrementing or decrementing something and definitely not creating a new object. Hence, it's not a valid statement, hence the error.

It's bad coding style, but something like this should work:

bool sink = DCC.systemFlags[1] ? sf1CheckBox.Checked = true : sf1CheckBox.Checked = false;

just because now you're actually doing something (assigning to sink).

Let me reiterate bad coding style again. You'll do so much better refactoring your code to what the others are saying in their answers.

Upvotes: 0

Dan J
Dan J

Reputation: 16708

If you just want to assign the value of one of the flags to the Checked property, all you need is this:

sf0CheckBox.Checked = DCC.systemFlags[1]

Further to your question, the ternary operator expects to return a value - it is not a replacement for an if() {} construct.

Upvotes: 2

satnhak
satnhak

Reputation: 9861

What you actually want is this:

sf0CheckBox.Checked = DCC.systemFlags[1] 

Upvotes: 4

user541686
user541686

Reputation: 210392

There is no shorthand for a generic if statement.

One statement does not a ternary operator make, in C# syntax. :(

Edit: Take a look at others' answers for a shorthand for this particular if statement.

Upvotes: 2

Related Questions