Index out of bound? What index?
Just curious.
Printable View
Index out of bound? What index?
Just curious.
I just tried that code and looked at the stack trace of the exception and it was actually thrown in the Microsoft.VisualBasic.Conversion.HexOrOctValue function. That suggests to me that, because the String starts with "&", it is looking for an "H" at the next index without checking that the next index exists.
That is a bug in Val but it may be there intentionally. VB Runtime functions were designed to have the same behaviour as the equivalent functions in VB6. If that's how Val behaved in VB6, they would have done that on purpose. If not then that's just a bug.
Of course, we never ever use Val because it's basically cr*p so it will never be an issue, right?
Val() is evil. Not as evil as Goto, but evil nevertheless.
And what's the replacement? Hand code parsing number?
If you know that it is definititely a number, then you can use CInt() or Integer.Parse (or the similar methods for the other numeric types). If you are not sure that the string can be completely converted into a number, then you would use Integer.TryParse. The first two will throw exceptions if the string cannot be fully converted into an integer.
There is a time when Val is still useful, but it is quite rare. The one time that it would be the best tool is if you have a string like "123AA", and wanted to get the 123 off the beginning. TryParse would return False, because the whole string can't be converted, and CInt or Integer.Parse would both throw exceptions. Of course, this will only work if the numbers are the first characters of the string and the rest doesn't matter. Also, Val will only ever return a double, which is less than ideal if you are trying to get an integer, as you would have a two step process.
Code:Dim textvals() As Sting = {"1234", "not a number"}
For Each txt As String In textvals
Dim parsedval As Integer
If Integer.TryParse(txt, parsedval) Then
' Parse successful
Else
' Not a number
End If
Next