
Question on passing array parameters to VB.NET Sub/Function
Quote:
> In the very first message, Sai said that *both* ways modify
> array data, so reasons 2 and 3 are no good
Arrays are reference types. When something is passed ByVal, a copy of the
content of the variable is passed. When it's passed ByRef, a reference to
the variable is passed. Both is also true for reference types. Passing a
variable of a reference type ByVal means that a copy of the reference is
passed (as the reference *is* the content). Changing this copy in the called
procedure (by assigning Nothing or a new array) keeps the passed variable
unchanged. It does not mean it keeps the content of the object referenced by
the variable unchanged.
So I'd say that reason two is still correct (the value is the *reference*
not the content of the array) whereas the third reason can really be
misunderstood. I meant that *the passed reference* can not be changed by
mistake.
Armin
Quote:
> > > I get what you are saying.
> > > My question is: Why would someone want to use ByVal to pass an
> > > array in the first place ? If they dont want the dimension
> > > changed then they dont write a ReDim in the Sub/Function,
> > > right ?
> > > What is the advantage of passing ByVal.
> > One minor reason is that you can reuse the variable for a new
> > array
> without
> > changing the passed array. More important is the fact that the
> > usage of byval documents that the procedure is not changing
> > the value, i.e. it is only an in-, but not an out-argument.
> > The third reason is that the array
> can
> > not be changed by mistake - not a real reason because that
> > would be a programming fault
> > Armin
> > > > > In difference from previous VB versions, you can use the
> > > > > ByVal keyword for array parameters to Subs/Functions in
> > > > > VB.NET
> > > > > However, since arrays are reference types, you end up
> > > > > passing a 4-byte pointer whichever way you choose to pass
> > > > > the array (i.e ByVal/ByRef)
> > > > > Both ways (ByVal/ByRef) succesfully modify array data.
> > > > > The only difference is that when you pass ByVal the ReDim
> > > > > statement doesnt affect the original array (whereas ByRef
> > > > > obviously does)
> > > > > Why then would anyone use ByVal at all ??
> > > > It keeps the passed reference from being changed:
> > > > Private Sub Form1_Load( _
> > > > ByVal sender As System.Object, _
> > > > ByVal e As System.EventArgs) _
> > > > Handles MyBase.Load
> > > > Dim a() As Integer = {1, 2}
> > > > MsgBox(a.Length)
> > > > PassByVal(a)
> > > > MsgBox(a.Length)
> > > > PassByRef(a)
> > > > MsgBox(a.Length)
> > > > End Sub
> > > > Sub PassByVal(ByVal a As Integer())
> > > > ReDim a(100)
> > > > End Sub
> > > > Sub PassByRef(ByRef a As Integer())
> > > > ReDim a(100)
> > > > End Sub
> > > > Armin