The conditional operator (? :)
By rickvdbosch
- 2 minutes read - 234 wordsEvery now and again I see a piece of code where the author has used the conditional operator ? : . It might be my tidyness or it might take some getting used to, but I don’t like it. I don’t like it at all! My gut feeling says it’s nasty, because it’s not easy readable code. Lets look at an example. Imagine you have a property getter for the count of a collection. When the ArrayList you use internally is null, you want to return 0, else you want to return the count of the internal ArrayList. With the conditional operator, this looks like this:
return (myArrayList == null) ? 0 : myArrayList.Count;
where ‘complete’ code writing would look like this, maybe even with an extra variable for the return value and just one return statement. (notice the brackets which you should always use imho):
if (myArrayList == null) { return 0; } else { return myArrayList.Count; }
Although the first code sample is much shorter, you also loose a lot of clarity by using the conditional operator. The second code sample explains what is being evaluated and when what value is returned. In short: I think the conditional operator needs two or three times reading to be sure what is being returned when, where the other sample doesn’t.
Sure, in this case the code might be simple to understand, but what happens when the expression being evaluated gets larger and more complex?