C# tricky ternary operator

C# has a way of letting you shorten up those short little if else statements into one line of code. It's called the ternary operator. Take the following code if something is meets our matching criteria set a value, else set another value. I've written a lot of these in my time as a coder.

So let's assume we have some integer we're using, we want to set a string based on that value. We know it needs to be in one of two ranges. We could write an if then else like below:

String result = String.Empty;

if( someInterger < 100 )
    result = "Less than a hundred";
    result = "Over a hundred";

With the ternary operator you can shorten it down to one line:

String result = someInteger < 100 ? "Less than a hundred" : "More than a hundred";

Now some might argue it's less readable and I agree to an extent but if you try it a few times you will find yourself writing a lot less small if/else blocks. You can take this a lot further down the road and do all sorts of useful things with it. If you're worried about others reading your code just be nice and leave them a little comment.


Anonymous said…
Your example is flawed, since:

bool result = 1 > 0;
bool result = 1 > 0 ? true : false;

yield the same results.

But yes, the ternary operator is nice. Most C/C++/C# programmers use it a lot.
Justin said…
Ah yes thanks for the comment. Using a boolean here is by far not optimal as you can do by far easier checks. I should put a better example up.

Popular Posts