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 trialMark Duplock
9,549 PointsTernary if
Can anyone tell me why my attempt on line 4 doesn't work, but line 5 does?
int value = -1;
string textColor = null;
(value < 0) textColor = "red" : textColor = "green";
textColor = (value < 0) "red" : "green";
2 Answers
Steven Parker
231,198 PointsActually, neither of those should work.
A ternary operation is identified by a question mark (?
), which is not present on either line.
But even if both lines had a question mark, it's important to remember that a ternary is not an if.
An if statement determines whether or not to execute another statement (or code block), but a ternary operator evaluates one of two expressions and returns the value.
Now in actual code, you might be able to cause assignments to occur as part of an expression evaluation, but you would have to be very careful about operator precedence in constructing your statement. Since any evaluation operation (including the ternary) takes precedence over assignment, what might look right would probably not compile. But even if you got around these issues, this is definitely not "good practice".
But here in the challenge, the "check work" function is specifically looking for a conventional application of the ternary.
Mark Duplock
9,549 PointsThanks for imagining thr ?'s in both lines Steven, not sure how they got missed. :)
Thanks for the explaination, that makes a lot of sense now.