0

I'm trying to use a ternary operator and am still learning so I'm not entirely familiar with how they do what they do.

I have a line of code that is as follows:

c.GetType() != typeof(CheckBox)
? c.Text = settingValue 
: ((CheckBox)c).Checked = bool.Parse(settingValue);

The purpose of this line of code is to test if the control c is of type CheckBox and then either set the text of the control or change the Checked state of the control. But this line gives me a CS0201 error in VS.

I know I could alternatively use an If statement for this but I wanted to see if I could condense it into one line with a ternary operator. What am I missing?

IneffaWolf
  • 73
  • 11
  • 2
    That's not how the ternary operator works - it's an operator so it returns one of two **values** depending on the conditional input. You're looking for an `if` statement - you want to *perform* one of two actions based on a conditional input. – J... Aug 31 '21 at 13:28
  • 1
    The use of the ternary is `var someVariable = condition ? value-to-set-someVariable-if-true : value-to-set-someVariable-if-false;` – Magnetron Aug 31 '21 at 13:32
  • 1
    First this is called the conditional operator (ternary just refers to how many operators it uses). And it requires a condition, and then two expressions that return a value of the same type. In your case you have a condition followed by an expression that returns a string and then one that returns a bool which is the problem. The typical usage is to do something like `var x = condition ? y : z;` where x is assigned y or z based on the condition. – juharr Aug 31 '21 at 13:32
  • Does this answer your question? [How does the ternary operator work?](https://stackoverflow.com/questions/463155/) and [Benefits of using the conditional ?: (ternary) operator](https://stackoverflow.com/questions/3312786/) –  Aug 31 '21 at 13:51

1 Answers1

4

It is not possible to do this with the conditional operator. Instead, use a normal if. It is also much more readable - don't always try to put as much code as possible into one line. You can use pattern matching in order to avoid a casting:

if(c is Checkbox cb)
{
    cb.Checked = bool.Parse(settingValue);
}
else
{
     c.Text = settingValue;
}
SomeBody
  • 7,515
  • 2
  • 17
  • 33
  • Thank you for your concise answer. I didn't know about the pattern matching also, that will help me in future. – IneffaWolf Aug 31 '21 at 15:09