Conditional operator in C#

This is an observation, not a complaint. I think all the instructors and courses here are outstanding. That said…

I’m about 75% through the Unity course, and I’m kind of surprised Ben hasn’t formally introduced the conditional operator yet. I’ve seen him introduce other concepts for the sake of efficiency, and I would have thought he’d do the same for the conditional. I’m only bringing this up because I’m going through a cleanup and saving a boatload of real estate by compacting a lot of if-else blocks today:

	if (Input.GetButton("Zoom"))
    {
        isZoomed = true;
    }
    else
    {
        isZoomed = false;
    }

becomes

    isZoomed = (Input.GetButton("Zoom")) ? true : false;

8 lines to 1 without breaking my formatting rules. And don’t you dare try to drag me into an argument about where curly braces belong. :stuck_out_tongue_closed_eyes:

4 Likes

It’s funny to see this cleaned up conditional statement example. I literally went over that in my C# class yesterday morning haha. :slight_smile:

1 Like

Hello Bitty,

I don’t know why a more concise refactor of the code wasn’t provided earlier in the course. I know from experience that some developers prefer the first example and avoid using the ternary operator unless it is more readable to do so. It’s personal preference and there’s no right or wrong way to do it. Do what makes sense for best readability in context.

In your second example, I believe you can simplify the assignment of isZoomed to be the result of GetButton, since it returns a bool.

isZoomed = Input.GetButton("Zoom");

I hope this helps.

Happy Coding :slight_smile:

1 Like

Privacy & Terms