Function Problem

usvpn

Freshman
Joined
Apr 19, 2010
Messages
45
Note from mod: Thread is cross-posted at XVBT.

Hi everyone :)
I have written a function which is a loop and is similar to old Val() function, I just wanna loop through all characters of an input string and return the numbers:
Visual Basic:
Private Function GetStrVal(ByVal InputString As String) As Integer
	GetStrVal = Nothing
	For MyLoop As Integer = 1 To InputString.Length
		If InputString.Substring(MyLoop - 1, 1) = 0 Or _
                 InputString.Substring(MyLoop - 1, 1) = 1 Or _
                 InputString.Substring(MyLoop - 1, 1) = 2 Or _
                 InputString.Substring(MyLoop - 1, 1) = 3 Or _
                 InputString.Substring(MyLoop - 1, 1) = 4 Or _
                 InputString.Substring(MyLoop - 1, 1) = 5 Or _
                 InputString.Substring(MyLoop - 1, 1) = 6 Or _
                 InputString.Substring(MyLoop - 1, 1) = 7 Or _
                 InputString.Substring(MyLoop - 1, 1) = 8 Or _
                 InputString.Substring(MyLoop - 1, 1) = 9 Then
			GetStrVal = GetStrVal + InputString.Substring(MyLoop - 1, 1)
		End If
	Next
End Function
It won't work and I get errors also I do believe there's a better way to compare if input is between 0 and 9? :confused:
Any idea?
 
Last edited by a moderator:
There's something I want to draw more attention to here (I'm surprised Atma didn't), and that's that you aren't using option strict.

The function supposed to return an integer, but in the first line inside the function, you set the return value to 'Nothing.' Nothing is used with reference types to indicate a variable doesn't hold a reference to anything. It seems VB is "helping" by converting Nothing to zero. Your code should probably read like so, so that what it actually does is clearer:
Visual Basic:
    GetStrVal = 0

Even though it sometimes makes things slightly more difficult, option strict should always be used because it forces you to do things the "right way". It might take a little longer to figure some things out when using option strict, but there is a reason that option strict requires you to do things certain ways.

Without option strict, VB tries to guess at what you are trying to do. More often it gets it right, and you get an automatic conversion that works. Still, it gets it wrong too often, and you get an automatic conversion that breaks your program. Since you will have typed in the code in a way that seemed to make sense, it will be very hard to figure out what is going wrong with your program when VB is automatically converting data types in a way that causes you issues.

I hope that was coherent. I'm a little tired.
 
Back
Top