Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Encapsulation and Arrays Ternary If

what am i doing wrong?

so i do have the boolean expression at the start (value < 0) but it will not let me proceed because it says i don't have the boolean expression

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

(value < 0) ? textColor = "red" : textColor = "green";
Receipt Box
Receipt Box
1,866 Points

I couldn't get what you wrote to compile in Visual Studio. I don't think it's possible to use the Ternary Operator to do anything other than assign a value - so you need to structure what you're doing differently, starting with either "return _" or "variable = _".

I changed it to this:

int value = -1;
string textColor = null;

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

The Treehouse page also gave me an error for a while - make sure you delete all the lines you started with. It'll throw an error if you just comment them out.

1 Answer

Steven Parker
Steven Parker
229,732 Points

:point_right: The ternary operator returns a value, but it doesn't have to assign it.

The result of a ternary operator can be used any way appropriate to a computed value, but you must do something with it. It could be part of an if expression, or a loop, for example. Also, it can contain complete statements as shown in the original code. The provided code can be made to compile and work (but not pass the challenge check) this way:

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

But this is certainly not a conventional usage. The suggestion by "Receipt Box" is more conventional, and will pass the challenge.

You can also pass the challenge by combining the assignment with the declaration of textColor on line 2:

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

Thank you that makes much more sense on ternary if operator. I was confused on when "Receipt Box" said I had to assign it to a variable when the video said i didn't