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

Evan Welch
Evan Welch
1,815 Points

Correct use of Ternary if statement

Are these two if statements equivalent? My code is not checking correctly. If askes me if I included the Boolean expression. I think I have included the boolean expression (value < 0). Any help would be appriciated!

int value = -1;
string textColor = null;

if (value < 0)
{
    textColor = "red";
}
else
{
    textColor = "green";
}

(value < 0) ? textColor = "red" : textColor = "green";
Reggie Williams
Reggie Williams
Treehouse Teacher

Evan Welch you can shorten this code by assigning the result to textcolor that way you don't have to repeat anything and the result is stored in the variable

variable = condition < 0 ? "value1" : "value2";

5 Answers

Evan Welch
Evan Welch
1,815 Points
value = -1;
string textColor = value < 0 ? "red" : "green";

This answer worked! Thank you Reggie Williams!

Evan Welch
Evan Welch
1,815 Points

Thank you Reggie Williams.

But, even when I compile my code as follows I do not pass the quiz.

int value = -1;
string textColor = null;

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

Thanks again.

Reggie Williams
Reggie Williams
Treehouse Teacher

Hey Evan Welch that's a bit closer but instead of writing textColor more than once you can assign the value of the ternary operation to textColor

textColor = condition goes here ? "option if true" : "option if false";
Evan Welch
Evan Welch
1,815 Points

Ok, I think I see what you mean. So I would write:

int value = -1;

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

Right?

Why doesn't this challenge accept the exact formatting we were just taught?

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

Reggie Williams
STAFF
Reggie Williams
Treehouse Teacher

Michael Musch be sure to start a new thread when you have a question so it doesn't get lost but this challenge is asking you to initialize the value variable so you'll want to use the above format that acts as a single variable definition. The example you provided also requires writing textColor twice which goes against the concept of D.R.Y or don't repeat yourself