Re: VB-101: Passing Arrays ByVal vs ByRef
- From: "Herfried K. Wagner [MVP]" <hirf-spam-me-here@xxxxxx>
- Date: Tue, 24 May 2005 11:46:58 +0200
"John Pass" <JohnPass@xxxxxxxxxxxxxxxxxxxxxxxxx> schrieb:
' procedure modifies elements of array and assigns ' new reference (note ByVal) Sub FirstDouble(ByVal array As Integer()) Dim i As Integer
' double each element value For i = 0 To array.GetUpperBound(0) array(i) *= 2 Next
' create new reference and assign it to array array = New Integer() {11, 12, 13} End Sub ' FirstDouble
Since the line where the values of the array 'array' are filled by the
values 11, 12 and 13 is the later part of the same sub-routine where the
earlier changes of values in the same array took place, I would expect these
values to be printed to the screen as output. To me, it looks like the array
values being returned to the calling function were first doubled and that
simply overwritten. Apparently this does not happen.
Arrays are reference types while 'Integer' is not. Consequently an array of integers is a reference type. By passing the array to the method using 'ByVal' the pointer to the array gets copied and the copy is passed to the method. Thus you can change the array's elements, but you cannot change the whole array. In other words, assigning a new array object to the paramater won't change the reference of the variable being passed to the method. You'll have to pass the array 'ByRef' in order to be able to do that.
--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>
.
- Follow-Ups:
- Re: VB-101: Passing Arrays ByVal vs ByRef
- From: John Pass
- Re: VB-101: Passing Arrays ByVal vs ByRef
- References:
- VB-101: Passing Arrays ByVal vs ByRef
- From: John Pass
- VB-101: Passing Arrays ByVal vs ByRef
- Prev by Date: Re: Maximized window cannot be minimized
- Next by Date: Re: 'System.NullReferenceException
- Previous by thread: Re: VB-101: Passing Arrays ByVal vs ByRef
- Next by thread: Re: VB-101: Passing Arrays ByVal vs ByRef
- Index(es):
Relevant Pages
|