ByVal and objects

  • Thread starter Thread starter Harry Simpson
  • Start date Start date
H

Harry Simpson

I've been going over the MS Application blocks and saw a sub procedure which
did not appear to change the value of the object passed in so i could'nt
figure out how the object's value got changed. A friend here told me that
what was going on was that if an object is passed into a sub even if ByVal
and within that sub the object is changed in any way, that change goes back
to the object that was originally passed in.

I've always used Functions to get values back and still think this is a good
practice so i had never run accross this before.
Pass in 17 and a table. Set a value in the passed in table to 50+17 and the
datatable on the original page now contains 67 not 17.

intNumber = 17
fooTable.Rows(0).Item("Value")=intNumber
MessWithNumber(intNumber, fooTable)

'The value of fooTable.Rows(0).Item("Value") here now will be 67 not 17.

Private Sub MessWithNumber(ByVal number As Integer, ByVal datatable As
DataTable)

number = number + 50

datatable.Rows(0).Item("Value") = number

End Sub

Of course everyone knew that right!

Harry
 
I am not clear on your question.

However, ByVal, for objects, means that a copy of the *reference* to the
object is made. Not a copy of the object itself - as this would be very slow
and memory consuming for large objects. So since only a copy of the
reference is passed - the object both references are pointing to, ist still
the same. There is still only one object in memory. So changing something
about the object in the function, will of course be seen in the caller -
because you are always talking about the same one object.

For value types (int,double, etc), a copy of the variable itself is made.
Thus, changing the variable in the function does not reflect back in the
original caller.
 
Marina,

Thanks for the splanation. Really wasn't asking a question. I just think it
is bad programming practice to change the value of objects with a sub
procedure in this matter. Go ahead and use a Function to return different
data and then modify the object.

Kind of just reverts back to byRef of variables.

Just making an observation.

Harry
 
Back
Top