C# Ternary conditional operator – Question mark in an if statement

I’m all for shortening the amount of code we write, if it makes it more readable.

One enhancement I make use of in C# is the ternary conditional operator.

Consider the following block of code:

            string input = "hi";
            bool saidHello;

            if (input = "hello")
                saidHello = true;
                saidHello = false;

In this example, we can see, the saidHello boolean value would be false,  as the input string actually said ‘hi’ rather than hello.

This could be shortened down to a single line like so (or 2, if we count the input initialisation)

            string input = "hi";
            var saidHello = input == "hello" ? true : false;

This makes use of the ternary operator.
The ? acts as a ‘then’ and the : acts as an else…

So you can think of it as something like below:

saidHello equals (if input equals hello then) true, else false.

These can of course be nested, as explained in this article, however in my opinion, this kind of defeats the whole point of this from my point of view – to increase readability of code.

Leave a Reply

Your email address will not be published. Required fields are marked *