Monday, May 7, 2012

Using Null Coalescing Part 2

Example 2: Make use of "ternary operator" :

You can even make use of ternary operator (?)  to evaluate null values. Here is how : -


string myValue = (newValue != null) ? newValue.Trim() : someDefaultValue;

But again it doesn't handles the situation we discussed in part 1.

What if myValue contains white-spaces? It will return empty string.

So, here is the modification: -

string myValue = (newValue != null) ? ((newValue.Trim()==string.Empty)? someDefaultValue: newValue) :  someDefaultValue;

hmm....look at the code, isn't that reduced the readability of code using couple of ternary operators. I am sure adding one more condition in it will definitely create a big head-ache to change / understand.

You can break the two ternary operators in two lines. But is that worth? Nah! it isn't.

So we tried hard to achieve a simple requirement. now what else? See - Using Null Coalescing Part 3



No comments:

Post a Comment