Home > Net >  Recursive value in a function
Recursive value in a function

Time:11-16

I am trying to develop a simple class-based function that will modify a previous value determined by the function, that is, it is a recurrence relationship.

In essence, I am developing my own random number generator which will work the same way the current Random class works, i.e.

Dim ran as New Random(123456)
For i = 0 To 9
   MessageBox.Show(ran.NextDouble & "  " & ran.Next(1,11))
Next

I can successfully do this using a class-based method simply by sending a value ByRef, but as you know for a method call, the old value to be modified needs to be placed inside the call to the method. Thus, I am trying to overcome use of a method or a global typed variable, and rather would like the instantiated class to somehow remember what the current value is.

The example code below attempts to multiply the value _value by 2 during every function call, so the expected result would be 2, 4, 8, 16, etc. However, even though a 2 is initially sent to the constructor, the value of _value is always returned as zero.

Class Example
    Public _value As Integer
    Public Sub New(ByVal _value)

    End Sub
    Public Function Value() As Integer
        _value *= 2
    End Function
End Class

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim x As New Example(2)
    For i = 0 To 9
        MessageBox.Show(x.Value)
    Next
End Sub

CodePudding user response:

Normally fields are Private. If you want to expose data from your class you would use a Public Property.

Change the name of the parameter for Sub New. If properly qualified your name will work but it is confusing. You must do something with the passed in value! Assign it to your field _value.

Your Function has no return value. It simply changes the value of _value. If you don't return anything use a Sub. Change the name of your Function to something meaningful. Add a Return statement to send a value back to the calling code.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim x As New Example(2)
    For i = 0 To 9
        MessageBox.Show(x.DoubleValue.ToString)
    Next
End Sub

Class Example
    Private _value As Integer
    Public Sub New(ByVal Input As Integer)
        _value = Input
    End Sub
    Public Function DoubleValue() As Integer
        _value *= 2
        Return _value
    End Function
End Class
  • Related