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. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Using Ternary Operators in CSharp
From Wiki
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:
- List<int> badNumbers = new List<int>();
- badNumbers.Add(7);
- badNumbers.Add(13);
- int ctr = 1;
- while (ctr <= 20)
- {
- Console.WriteLine("I will only print good numbers {0}!!!", ctr);
- if (badNumbers.Contains(ctr + 1))
- ctr += 2;
- else
- ctr++;
- }
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:
- while (ctr <= 20)
- {
- Console.WriteLine("I will only print good numbers, with less code {0}!!!", ctr);
- ctr = badNumbers.Contains(ctr + 1) ? ctr + 2 : ctr + 1;
- }
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)



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