Search code examples
vb.netif-statementiif

My nested IIF statement isn't modifying a string as expected in VB.NET


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'?


Solution

  • 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))