Beginning C# - Part 9: Ternary Operator | Ray Wenderlich

In this episode, you'll learn about the ternary operator as well as be introduced to nullable types.

This is a companion discussion topic for the original entry at
1 Like

Hello Brian, really excellent series so far. Very much looking forward to the next screencasts!

Hey @vegetarianzombie i had reached out another solution for this problem by simplyfing a little bit the sentence:

displayName = (playerName != "") ? "Hello " + playerName : "Hello player one";

what is the difference by this and if i don’t use any null comparison?


@bdmoakley Can you please help with this when you get a chance? Thank you - much appreciated! :]

Right now, you are just checking to see if the string is empty as opposed to if the string is null. In your example, a null string will still be validated since it is isn’t an empty string. This means, a null string will result in the “Hello” + playerName condition as opposed to the “Hello player one” condition.

1 Like

Hello! In the challenge I was confused as to why the order in which you have the two conditions matters, I ran them in both orders and got the same outcome. Would I be correct in saying the order doesn’t matter in this particular situation? If yes, then would the order only matter if I was trying to access properties of the string in the conditional? Thanks in advanced.

Order can matter in certain cases. Take this statement

if (monsters != null && monsters.Count > 0) 

Here we check to see if the monsters list is null in the first condition, and in the second condition, we check the count of the list. The code first checks to see if the reference is null. If it is null, it skips the second check. If you reversed the order and the monsters list was null, the app would crash. In some cases, order won’t matter. It’s really a case by case basis.

Thanks a lot, really helped to clear it up.

Hey, started watching this series after watching the majority of the YouTube series that got shifted over here and just a bit confused about the formatting of the series. I found having the challenge worked out and discussed useful for when I didn’t understand and used it as a way to determine if I really understood the lesson. But it seems like up until this episode, there were no explanations shown in the videos, like how it was in the end here. I know the answers were given in the zip file, but it doesn’t really work out as well when I try to use that. Just doesn’t ‘click’ as well, I guess.
Kind of a too little too late bit of criticism, but I still felt like it was worth noting.

Thanks for passing on the feedback. Did you manage to understand the core concept or are you still stuck? Feel free to reach out if you need any assistance.