Error when trying to use a ternary operator in C#
Here's my code:
public void ToggleCheckBox()
{
if (chk开发者_StackOverflow社区Selected.Checked) ? chkSelected.Checked = false : chkSelected.Checked = true;
//This works, but I want to write it using a ternary.
if (chkSelected.Checked)
{
chkSelected.Checked = false;
}
else
{
chkSelected.Checked = true;
}
}
What did I mess up on? Thanks!
Either do this:
if (chkSelected.Checked) chkSelected.Checked = false; else chkSelected.Checked = true;
...or this:
chkSelected.Checked = chkSelected.Checked ? false : true;
Or abandon the check and do this:
chkSelected.Checked = !chkSelected.Checked;
Write this as
chkSelected.Checked = !chkSelected.Checked
instead.
To rewrite your exact example, it get's messy like this:
chkSelected.Checked = (chkSelected.Checked) ? false : true;
The ?:
operator returns, in this case, either true
or false
. It cannot perform assignment.
You're using assignment instead of comparison, and you don't need an if
there. In fact, it isn't too clear what your intent is, but I'd guess it is:
chkSelected.Checked = !chkSelected.Checked;
Why not do:
chkSelected.Checked = !chkSelected.Checked;
Also, it does not compile, because of the if
you put in front of it. Remove that and it will work as well!
I think you mean:
chkSelected.Checked=(chkSelected.Checked ? false : true)
which can be shortened to:
chkSelected.Checked=!chkSelected.Checked
Because you have to use like a assignation:
chkSelected.Checked =(chkSelected.Checked ? false : true);
Ternary operator is used like a assignation
But here It is not really a good idea to do that here and do
chkSelected.Checked =!chkSelected.Checked;
Shorter way..
精彩评论