Quantcast
Channel: Alex Brown » tips and tricks
Viewing all articles
Browse latest Browse all 2

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

$
0
0

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;
            }
            else
            {
                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)

; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true; ]            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.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images