|
-
Mar 22nd, 2011, 01:21 AM
#1
Thread Starter
Fanatic Member
Why do I get error if I do val("&")
Index out of bound? What index?
Just curious.
-
Mar 22nd, 2011, 01:38 AM
#2
Re: Why do I get error if I do val("&")
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?
-
Mar 22nd, 2011, 02:56 AM
#3
Re: Why do I get error if I do val("&")
Val() is evil. Not as evil as Goto, but evil nevertheless.
-
Mar 24th, 2011, 11:19 AM
#4
Thread Starter
Fanatic Member
Re: Why do I get error if I do val("&")
And what's the replacement? Hand code parsing number?
-
Mar 24th, 2011, 11:25 AM
#5
Re: Why do I get error if I do val("&")
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.
My usual boring signature: Nothing
 
-
Mar 24th, 2011, 12:30 PM
#6
Re: Why do I get error if I do val("&")
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|