Link to home
Start Free TrialLog in
Avatar of gbmcneil
gbmcneil

asked on

Return Values From A Function

Hello Experts -

Got a question. I've got a simple function that conceptually looks something like this:

Public Function DoSomething ( Value1, Value2 )
      blah, blah...
      DoSomething = 123
End Function

Now let's say that in the process of arriving at the result ("123"), Value1 changes from what was the intially passed value. Let's say Value1 was 1. And, in the course of calculating, Value1 becomes the value 5.

It seems in VB.NET that to the calling program, Value1 always remains a 1. That's both before and after the function is called.

This seems to be very desirable because it prevents the calling program from becoming contaminated from bugs in the Function DoThing.

But, how about on occasions when you would like more than one value being returned. You wanted to know if Value1 had changed and you want to know its new value.

Is it possible to tell VB.NET that you want Value1 to change when control is returned to the original program?

Sorry, but Iif the answer seems obvious , you should realize that I never took a programming course.

 


ASKER CERTIFIED SOLUTION
Avatar of wellhole
wellhole

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This could be accomplished in a couple of ways, but the easiest way would be to Dim the variables you want in the calling function, then pass them ByRef to DoSomething.  This way, any changes to any of the variables is automatically updated in the calling function.  Example:
Public Sub Main()
    Dim intVariable1 As Integer
    Dim intVariable2 As Integer
    Dim intResult As Integer
    
    intVariable1 = 1
    intVariable2 = 5
    intResult = 0

    intResult = DoSomething(intVariable1, intVariable2)
End Sub

Private Function DoSomething(ByRef Value1 As Integer, ByRef Value2 As Integer) As Integer
    Dim intCalculation As Integer
    
    Value1 = Value2 + 2
    
    intCalculation = Value1 * Value2
    
    Return intCalculation
End Function

Open in new window


Here's a decent explanation: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/07b9d3b9-5658-49ed-9218-005564e8209e/
Avatar of gbmcneil
gbmcneil

ASKER

Gee, I appreciate your input here G Hosa Phat. But, I think that wellhole answered the question first.

And, his solution works.

Many thanks to both of you. I obviously didn't know the difference between ByVal and ByRef. Now, I do.
All good.  I can get a bit carried away sometimes.  Glad you got what you needed.