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.Ch开发者_开发百科ecked = 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.
What you actually want is this:
sf0CheckBox.Checked = DCC.systemFlags[1]
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
).
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.
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.
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.
精彩评论