PDA

Click to See Complete Forum and Search --> : byval array changes when giving value


sarris
Feb 18th, 2007, 09:30 AM
hi there,
i am coming accross i weird problem
i have this structure
Public Structure Pack_
Dim pack() As Byte
Dim comport As Integer
Dim toRouter As Boolean
Dim header As header_
End Structure

and declared globaly dim pack as pack_
and initiated at the form_load pack = new pack_

i have this function
myfunction(byval dim Wpack() as byte)

pack.pack =wpack

pack.pack(4) = 30
end function

for some reason, wpack(4) becomes 30 as well...
i dont get it at all...

sarris
Feb 18th, 2007, 09:45 AM
ok i think i got the problem...the pack.pack = wpack doesnt really work.
I copied the elements of wpack to pack.pack one by one and the problem was solved.
But still i dont really get it why that happened

jmcilhinney
Feb 18th, 2007, 06:33 PM
That's exactly what should happen. When you pass a parameter by value it is the variable you cannot change. That means that if you pass an array object by value and you assign a new array object to that variable then that change will not be reflected after the method completes. It doesn't mean that you can't make changes to the object that the variable refers to, so any changes you make to the elements of the array will be reflected after the method completes. If you don't understand the difference between value types and reference types then this may be a bit confusing, but if you do understand that difference then it's perfectly logical.

What exactly are you trying to do in that method anyway? Are you trying to copy the contents of one array to another and then change one element of the new array? If so then use the Array.Copy method. By this line:pack.pack =wpackyou are saying pack.pack now refers to the same object that wpack refers to. If you don't understand that then think about your mother. Who is your father's wife? Are they two different ways to refer to the same person? Yes they are, and programming is the same.

Shaggy Hiker
Feb 18th, 2007, 08:31 PM
By the way, don't you get all your various packs confused? I try to avoid naming a member variable to the same name as a variable I might use outside the object.

sarris
Feb 21st, 2007, 01:36 PM
Ok, thanks a lot!!