Tuesday, October 28, 2014

Careful with IIF in VB.NET

In VB.NET, We generally use ternary operator, IIF. Today we came across with some atypical behaviors.

 Dim a As Boolean = True 
        Dim b As Integer = 1 
        Dim c As Integer = Nothing   
        Dim d As Integer = CInt(IIf(a = True, b = 3, c.ToString()))  
What is the result?
It throws error. Null cannot be converted to string.
 But if we use same statements with IF..ELSE, it will give you correct result.

If (a = True) Then 
            b = 3 
        Else 
            Response.Write(c.ToString()) 
        End If 
It works fine.
First observation:  In IIF, it evaluates both true and false conditions. That’s why it gives error.

Another example:
 Dim a As Boolean = True 
        Dim b As Integer = 1 
        Dim c As Integer = 2   
        Dim d As Integer = CInt(IIf(a = True, b = 3, c=4))  
What is the value of B now?
It should be 3, right?

But, it will be 1. Yes One 

Second observation:
a= true is right, so it goes to b=3 statement. 
But it won’t consider it as assignment, instead it treats as conditional EQUAL operator. So b= 3 means is 1=3 ? 
Obviously 1 is not equal to 3. So it returns false, which is 0.

Note: When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values become True.

So my dear folks, please be careful while using IIF in VB.NET. Few things seems to be simple but very dangerous.

No comments: