I’m having to write some VB code for a website that we maintain at work. Although I write everything in C# now (wouldn’t everyone?) it’s a legacy site so it’s a case of deal with it rather than rewriting everything in C#.
I needed to do a ternary operation which in C# is easy and works as you’d expect it to. However in VB it seems that both parts of the ternary are evaluated irrespective of which is the one that is really going to be ran.
So the following code doesn’t actually work:
strKeyword = IIf(intEnd = -1, strKeywords.Substring(intStart, intEnd - intStart), strKeywords.Substring(intStart))
If intEnd is –1 (which in this case it is if the value I’m looking for is at the end of the string) then I want the false (second) part of the ternary to execute taking the string from the value of intStart. However that’s not what happens! VB evaluates both and throws an error on the true (first) part – even though it’s never going to be executed. Bah!
So in the end I’ve got to go with the much less elegant normal If statement as follows:
If (intEnd <> -1) Then
strKeyword = strKeywords.Substring(intStart, intEnd - intStart)
Else
strKeyword = strKeywords.Substring(intStart)
End If
Do I need anymore reasons to run away from VB and develop exclusively in C#'?
No comments:
Post a Comment