JefE
JefE

Reputation: 137

How to use Function return

I'm wondering if this is the right way to do this. I have this sample code that should represent a user action, and a calculation done in a function, this function should then return the value to my sub?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer = 1
    Test_function(i)
    MsgBox(i)
End Sub

Private Function Test_function(ByVal i As Integer)
    i = i + 1
    Return (i)
End Function

When i run this piece of code I get:

i = 1 in sub

i = 2 in function

i = 1 in sub?

How do you get the i = 2 into my sub? Or is this not the correct way of using this?

Upvotes: 1

Views: 91

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

There is nothing to wonder, it's only a simple misunderstanding. you are printing the actual value of i if you Call like this:

MsgBox(Test_function(i))

Then both will be the same; or you can check this in following way:

Dim tempVal = Test_function(i)'<-- will give 2
MsgBox(i)'<--- will give 1

this is because you are passing the value of i not i as reference, if you pass it as reference then also both will be the same. So if you change the function signature as follows:

Private Function Test_function(ByRef i As Integer)
    i = i + 1
    Return (i)
End Function

same function call will give you both values as 2

 Dim tempVal = Test_function(i)'<-- will give 2
 MsgBox(i)'<--- will give 2

Reference ByVal and ByRef

Upvotes: 1

tom.dietrich
tom.dietrich

Reputation: 8347

I think what you're asking is why does i not get changed by the call to Test_function.

Let's break down your code.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer = 1 'creating a variable named i, value 1.
    Test_function(i) 'passing the value of the variable i to test function, but not doing anything with what the function returns.
    MsgBox(i) 'calling messagebox with the value i.
End Sub

Private Function Test_function(ByVal i As Integer) 'creating a new variable also named i with the value being passed in.
    i = i + 1 'incrementing the value of the i variable by 1.
    Return (i) 'returning i 
End Function

So there are a few concepts that you're misunderstanding as far as I can tell- what ByVal means, perhaps the concept of variable scoping, as well as what Return does.

The obvious answer is that you're not using the value returned by Test_function. If you had i = test_Function(i), then i would be incremented by the call to Test_function

Another approach would be to pass i ByRef instead of ByVal- if you did that, the i in the scope of your Test_function method would be the same as the i in the scope of your Button1_Click method. But because you are passing it ByVal, the i variables are actually two completely different variables.

Upvotes: 4

Related Questions