August 15, 2018

Using ternary operator to write less code

Ternary operator within your code? Lets see some simple example!

Using ternary operator to write less code

Say for example, you have a situation where you want to return true if the number is bigger than 10. This is how you would normally code it:


    int magicNumber=15
    bool biggerThan10
    if magicNumber > 10
    biggerThan10 = true
    else
    biggerThan10 = false


We could reduce the number of lines that we need to write by using a ternary operator.


    int magicNumber=15
    bool biggerThan10
    biggerThan10 = magicNumber > 10


Eh wait, I didn't even need a ternary operator for that. Let's try again.

Say that we want to return different strings for two different conditions. This is how we could write our code:


    bool isCooked = true;
    string tellTheChef;

    if isCooked
    tellTheChef = "It is cooked!"
    else
    tellTheChef = "It isn't cooked!"


Now rewriting this using a ternary operator, this is how we would do it:


    bool isCooked = true;
    string tellTheChef = isCooked ? "It is cooked!" : "It isn't cooked!"
    

It reduces the number of characters that you need to write and your fingers will be grateful for it.