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

Help. Can I get help with the boolean expression?

In the previous video, we saw how a ternary if statement could be used in place of an if/else statement to determine the value to return from a method. Ternary if statements can also be used to determine the value to use when initializing a variable. Use a ternary if statement instead of an if/else statement to initialize the textColor variable to the string value "red" if the value variable is less than "0", otherwise initialize the textColor variable to the string value "green".

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

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

5 Answers

Jon Wood
Jon Wood
9,884 Points

So it's asking you to change the if/else statement into a ternary statement. What you should do is something like this: string textColor = {boolean expression} ? {what to return if true} : {what to return if false}

Hope that helps, but let me know if you need more details.

i did what you said but its still giving me a bummer int value = -1; string textColor = null; string textColor = {value < 0} ? {textColor = "red"} : {textColor = "green"} help

return textColor = (value < 0) ? textColor = "red" : textColor = "green"; why is this not working?

Nevermind I got it.

Krystal Welch
Krystal Welch
1,067 Points

What did you do? I'm getting an error saying : Bummer! Did you include the "red" and "green" string literal expressions (separated by a colon) to the right of the ternary operator?

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

Steven Parker
Steven Parker
231,268 Points

You can't use return except in a function, you don't need it here. And don't try to assign inside the ternary expression, just put the possible values there. Take another look at Jon's example of how to format it.

Steven Parker
Steven Parker
231,268 Points

The "boolean expression" is the same one in the if statement.

Jon's given you a good generic example of the ternary itself, but it seemed like you were asking specifically about the boolean expression used in the ternary? That's just the same as the boolean expression used in the if statement in the original code.

Steven Parker
Steven Parker
231,268 Points

Congratulations to Jesse and Krystal on resolving your issue! :+1: