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

Josh Gallacher
PLUS
Josh Gallacher
Courses Plus Student 3,325 Points

Could someone please help break down for me step by step what exactly is happening in a ternary if statement?

I followed along with the video just fine but when I got to the code challenge I realised that I clearly don't understand what exactly is happening and why.

The way I read my code is that is that the '?' will return for if and the ':' will return for else but I keep getting asked if I included the boolean expression which I'm sure is the '<'. I had to break from studying for 2 or 3 months and am just coming back to it now which makes me wonder if I'm missing something obvious that I'll kick myself for when I see it. Thanks guys!

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

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

2 Answers

andren
andren
28,558 Points

Your understanding of the ternary if statement is actually correct, the error message you are receiving is a generic error that is produced if your code does not work properly.

The reason why your code does not work is that you are missing an = between textColor and the ternary if, which is needed to actually assign the returned result. Like this:

int value = -1;
string textColor = null;

textColor = (value < 0) ? "red" : "green";
Josh Gallacher
PLUS
Josh Gallacher
Courses Plus Student 3,325 Points

I knew it would be something I'd kick myself for! Thank you!