byval array changes when giving value
hi there,
i am coming accross i weird problem
i have this structure
VB Code:
Public Structure Pack_
Dim pack() As Byte
Dim comport As Integer
Dim toRouter As Boolean
Dim header As header_
End Structure
and declared globaly and initiated at the form_load i have this function
VB Code:
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...
Re: byval array changes when giving value
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
Re: byval array changes when giving value
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:you 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.
Re: byval array changes when giving value
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.
Re: byval array changes when giving value