ByVal and ByRef in VB.Net

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all, I wrote this sample code :

Private Sub Button1_Click( ..... ) Handles Button1.Click
Dim x As New ArrayList
x.Add(1)
x.Add(1)
TestArrayList(x)
MsgBox("TestArrayList : " & x.Count.ToString)
End Sub

Private Sub TestArrayList(ByVal lst As ArrayList)
lst.Add(1)
lst.Add(1)
lst.Add(1)
End Sub

When I wrote it, I was sure to see in the message box that the ArrayList
have 2 items, because TestArrayList use the "lst" parameter ByVal. But, when
I ran that, I saw in the message box that the arraylist have 5 items....

Can you explain me what append here ?

Thanks a lot

Michel
 
ByVal refers to the variable. For objects, it means a copy of the pointer to
the object is passed, as opposed to the original pointer. Meaning if you
were to say lst = Nothing, the x variable would not be effected. If you were
to pass ByRef, 'x' would actually be Nothing after the function call.

Under no conditions would the entire object ever be copied - not only would
this be a performance and memory nightmare, but often times it would raise a
lot of questions about whether object that this object points to needs to be
copied, etc.
 
Because although you are passing the array ByVal, an array is a Reference
Type. When you pass a reference type ByVal, you are not passing a copy of
the reference type, but instead you are passing a copy of the pointer to the
original reference type. You wind up with 2 pointers (in your case: x and
lst) that point to just one object (your array).

Only when you pass a value type (integer, date, Boolean, decimal, etc.)
ByVal do you get a copy of the data to work with.
 
Michel said:
Hi all, I wrote this sample code :

Private Sub Button1_Click( ..... ) Handles Button1.Click
Dim x As New ArrayList
x.Add(1)
x.Add(1)
TestArrayList(x)
MsgBox("TestArrayList : " & x.Count.ToString)
End Sub

Private Sub TestArrayList(ByVal lst As ArrayList)
lst.Add(1)
lst.Add(1)
lst.Add(1)
End Sub

When I wrote it, I was sure to see in the message box that the ArrayList
have 2 items, because TestArrayList use the "lst" parameter ByVal. But, when
I ran that, I saw in the message box that the arraylist have 5 items....

Can you explain me what append here ?

Thanks a lot

Michel
 
Back
Top