0
votes

I wrote this nested IIF statement to determine if a string containing a URL contains http:// or https:// so that I can include it if necessary.

IIf(urlLong.Contains("http://"), Nothing, _
            IIf(urlLong.Contains("https://"), Nothing, _
                urlLong = "http://" + urlLong))

However when running this I get no result. I've tried re-writing it to get the simplest possible IIF statement working but even this doesn't work as expected.

IIf(urlLong.Contains(urlLong), Nothing, urlLong = "http://" + urlLong)

Which would lead me to believe that I don't quite understand how IIF statements work. I got the code to work by creating a function to add the "http://" and my code now looks like this

IIf(urlLong.Contains("http://"), urlLong = urlLong, _
        IIf(urlLong.Contains("https://"), urlLong = urlLong, _
            addHttp(urlLong)))

Where addHttp takes urlLong ByRef and adds the http://

Private Function addHttp(ByRef urlLong As String) As String
    urlLong = "http://" + urlLong
    Return urlLong
End Function

So, my questions are, why doesn't the first IIf statement work where the second one does and is there an alternative way to do this which would be considered more 'best practise'?

3
Do not use IIF in VB.NET, the ternary operator with short-circuit evaluation is IF(expression, true, false) - Steve

3 Answers

0
votes

https://msdn.microsoft.com/en-us/library/27ydhh0d(v=vs.90).aspx

You cannot assign value directly inside the IIF statement, because it is returning value in the TRUE or FALSE parts, so you have to assign it to a new variable

Dim newUrl = IIf(urlLong.Contains("http://"), Nothing, _
                IIf(urlLong.Contains("https://"), Nothing, _
                    "http://" + urlLong))
0
votes

IIF has a return value should be used like this:

var newUrl = IIf(urlLong.Contains("http://"), urlLong, addHttp(urlLong))
0
votes

IIF does not work in the way you are trying to use it. It is equivalent to the following:

Public Function IIF(evaluator as Boolean, resultIfTrue As Object, resultIfFalse As Object) As Object
    Dim trueResult As Object = resultIfTrue
    Dim falseResult As Object = resultIfFalse
    If evaluator Then
        Return resultIfTrue
    Else
        Return resultIfFalse
    End If
End Function

So you can nest another IIF in the resultIfFalse part, but you need to assign the final result back to the variable like this:

Dim result = IIF(test, "worked", IIF(test2, "worked", "failed"))

Note that you should really be use the If Operator in .Net. The usage is basically identical, but it is type safe and more efficient.

Dim result = If(test, "worked", If(test2, "worked", "failed"))