Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Objects Encapsulation and Arrays Ternary If

abdur rafay
abdur rafay
1,933 Points

I don't understand what I am doing wrong?

The formatting of the ternary if is correct, there are no compiler errors either.

int value = -1;
string textColor = null;

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

2 Answers

Steven Parker
Steven Parker
221,902 Points

The ternary operator should be used as an expression, not as a control statement. Try coding it as a single assignment, with the entire ternary on the right side, and the true/false clauses holding only the values to be chosen. Example:

string YesNo = boolValue ? "Yes" : "No";
Victoria Holland
Victoria Holland
6,159 Points

I also got caught out by this!

I originally had value < 0 ? textColor = "red" : "green";

but it turned out I needed to swap the condition and the variable name like this: textColor = value < 0 ? "red" : "green";