It's still horrible code.
As written, you invoke the function
MathOne( ) each time through the loop in the
MathTwo( ) function.
So you duplicate all that work creating an array, filling it with cosine numbers, etc., 20 times!
At a minimum, you should have written something like
Function MathTwo() As Array
Dim ArrayTwo(20) As Double
Dim m1 As Array = MathOne( )
Dim t As Double = 0
For i As Integer = 0 To 20 Step 1
ArrayTwo(i) = Sin(t)^2 + m1(i)^2
t += PI / 10
Next
Return ArrayTwo
End Function
Won't solve the late binding problem/question, but will perform 20 times better.
There are several ways to fix the late binding problem.
If you really insist on calling MathOne() 20 times in your loop (ugh), then you could do it by simply coding:
ArrayTwo(i) = Sin(t) ^ 2 + CType(MathOne(), Double())(i) ^ 2
Another way would be to change my code above from
Dim m1 As Array = MathOne( )
to
Dim m1 As Double() = CType(MathOne( ), Double() )
But, of course, probably the best way would be to avoid the use of the undifferentiated type
Array and declare the functions as
Function MathOne( ) As Double( )
and
Function MathTwo( ) As Double( )
which, in my mind, is by far the cleaner way. (But be sure to still do the
Dim m1 As Double() = MathOne()
of course! To avoid the extra 19 calls to MathOne funciton.)
And, yes, I can think of a handful of more ways this could be done.
Anyway, if you were trying to test my knowledge, you didn't try too hard.
****************
What the heck...here's the cleanest way, as I see it. Changes (think I got them all) from your code are in red:
Code:
Public Class Form1
Function MathOne() As Double()
Dim ArrayOne(20) As Double
Dim t As Double = 0
For i As Integer = 0 To 20 Step 1
ArrayOne(i) = Cos(t)
t += PI / 10
Next
Return ArrayOne
End Function
Function MathTwo() As Double()
Dim ArrayTwo(20) As Double
Dim m1 As Double() = MathOne()
Dim t As Double = 0
For i As Integer = 0 To 20 Step 1
ArrayTwo(i) = Sin(t) ^ 2 + m1(i) ^ 2
t += PI / 10
Next
Return ArrayTwo
End Function
End Class