IIf behavior question

olsonpm

Well-known member
Joined
Aug 24, 2010
Messages
46
Programming Experience
Beginner
IIf statement - I don't understand the behavior in this context.

VB.NET:
Private Function returnsInt() As Integer
    IIf(False, returnsInt = 2, returnsInt = 4)
End Function

public sub main()
    MsgBox(returnsInt())
end sub

Why would returnsInt return a 0 every time? I was thinking it should return 4 both when the boolean was true and false. The reason i ask is that I am reading through someone else's code and to understand it I tried emulating it. If it were up to me, I'd be using return statements.

thanks for your help,
Phil

Edit: I now think it's because the IIf statement returns a value, and thus is being used incorrectly in this case. Is there a version of vb where the above code works as the programmer intended? I know this guy is older than me, so he might be used to coding in an older version.
 
Last edited:

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
Think about what's going on with that code & what you want it to do, the IIf() returns one of the two values (the true part or the false part) and you want to assign the value to the function as the return value, so if you break it down:
VB.NET:
Private Function returnsInt() As Integer
    If True Then
        returnsInt = 2
    Else
        returnsInt = 4
    End If
End Function
So to wrap that up into a single line you want:
VB.NET:
Private Function returnsInt() As Integer
    returnsInt = IIf(False, 2, 4)
End Function
which is not what your code does at all:
VB.NET:
Private Function returnsInt() As Integer
    IIf(False, returnsInt = 2, returnsInt = 4)
End Function
So why you're getting a zero all the time is because inside the IIf() you're evaluating returnsInt = 2 or returnsInt = 4 instead of assigning it and since nothing is assigned the function is returning it's default integer value, which is 0.

However I would do it the .Net way instead of the crappy legacy vb6 way:
VB.NET:
Private Function returnsInt() As Integer
    Return If(False, 2, 4)
End Function
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,335
Location
Sydney, Australia
Programming Experience
10+
IIF means if and only if right?

It means "inline if". From VB 2008 onwards you should use the if operator instead, which is generic and short-circuits.
 
Top Bottom