Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Using Ternary Operators in CSharp

From Wiki

Jump to: navigation, search

Imagine you have some silly task assigned to you. For the sake of discussion, we'll say you need to increment a number, but you need to skip the numbers 7 and 13 because your boss is superstitious. So you can do that like this:

  1. List<int> badNumbers = new List<int>();
  2. badNumbers.Add(7);
  3. badNumbers.Add(13);
  4.  
  5. int ctr = 1;
  6.  
  7. while (ctr <= 20)
  8. {
  9.     Console.WriteLine("I will only print good numbers {0}!!!", ctr);
  10.  
  11.     if (badNumbers.Contains(ctr + 1))
  12.         ctr += 2;
  13.     else
  14.         ctr++;
  15. }

Not too bad, you will probably keep your job with this. But what if he's got you coding this a lot, you sure don't want to be typing out the whole If statement every time. So, how can we save a few keystrokes?

Luckily C# offers ternary operators. Javascript fans will know these already, but for non-js fans it goes something like this:

var toAssign = boolean_to_check ? value_if_true : value_if_false;

So, for the above example our while loop becomes this:

  1. while (ctr <= 20)
  2. {
  3.     Console.WriteLine("I will only print good numbers, with less code {0}!!!", ctr);
  4.  
  5.     ctr = badNumbers.Contains(ctr + 1) ? ctr + 2 : ctr + 1;
  6. }

While these are fun, I don't use them very much because I think they decrease code readability and they get ugly if you need to test complex logic. However, they can certainly come in handy (for loop declarations come to mind).

contributed by --AlexCuse 21:29, 2 July 2008 (GMT)

501 Rating: 2.5/5 (45 votes cast)