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

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
seal-mask
.a{fill-rule:evenodd;}techdegree
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
seal-mask
.a{fill-rule:evenodd;}techdegree
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
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
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