C# C# Objects Encapsulation and Arrays Ternary If

daniel benisti
daniel benisti
11,901 Points

why is there an error

what is wrong in my code?

int value = -1;
string textColor = null;

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

1 Answer

Steven Parker
Steven Parker
203,176 Points

The ternary operator creates an expression, it's not a control statement. So instead of embedding assignments within it, assign the result of the entire expression to the variable:

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