C# C# Objects Encapsulation and Arrays Ternary If

Sarah Newton
Sarah Newton
2,178 Points

Why is this ternary operator not valid?

I believe this is written correctly yet the challenge fails to recognize the boolean operator. Am I missing something obvious here?

CodeChallenge.cs
int value = -1;
string textColor = null;

(value < 0)
    ? textColor = "red" 
    : textColor = "green"

1 Answer

andren
andren
28,391 Points

The ternary operator is valid, but the way you use it is not. The ternary operator returns a value based on the expression you give it. So instead of placing an assignment in the true and false section you should just type the value that should be assigned. And then assign the ternary operator to the textColor like this:

textColor  = (value < 0) ? "red" : "green";

You had also forgotten to end the ternary operator with a semicolon. And while it is allowed to break the operator onto separate lines it is not usually done unless the values are long enough to warrant it. Since part of the point of the ternary operator is that it is pretty space efficient.