IIF(A,B,C) -- Beware it is a function not a statement!!

Learning how to write neat and clean is something many people wish to achieve. I believe it's an art which can be mastered with practice. I myself have this habit of keeping things brief and to the point, and I always tend to apply the same theory to my coding as well. However, today while writing a small piece of code in the similar consise manner for a small module, I found something interesting that made me realize the importance of understanding the difference between different programming constructs. I am talking about IIF(A,B,C) function and IF ELSE statement in particular here.

I had a situation where I was getting some value from the database and there was a fair chance of that value being NULL. I preferred IIF over IF ELSE to save 3 lines of code.

Dim lCVCount As Integer = IIf(IsDBNull(DataBinder.Eval(e.Item.DataItem, "IsCV")), 0, CInt(DataBinder.Eval(e.Item.DataItem, "IsCV")))

Mucy to my surprise, it didn't work and threw me exception. I kept wondering for a few minutes what is wrong with this. You know it is generally said that not knowing something is acceptable but forgetting something which you know is completely unacceptable and I agree with this. How can I forget that a function behaves differently than a statement. It passes parameter values to calle which means it must execute those parameters first, if they are found to be compund in order to get their value. This explains it all that why the third parameter in above statement is throwing exception. I thought I am better off using IF ELSE here in order to keep .NET runtime happy.

Sometimes It is good to get these kinds of errors which reinforces the fact that we should always be careful in what we write and specially when it comes to writing code!!

HTH,

0 comments:

Post a Comment