Visual Basic.NET 2008 > Programming Fundamentals

Passing Objects as Arguments - Argument-Parsing Mechanism in VB.NET 2008

When you pass objects as arguments, they're passed by reference, even if you have specified the ByVal keyword. The procedure can access and modify the members of the object passed as an argument, and the new value will be visible in the procedure that made the call.

The following code segment demonstrates this. The object is an ArrayList, which is an enhanced form of an array. The ArrayList is discussed in detail later in the tutorial, but to follow this example all you need to know is that the Add method adds new items to the ArrayList, and you can access individual items with an index value, similar to an array's elements. In the Click event handler of a Button control, create a new instance of the ArrayList object and call the PopulateList() subroutine to populate the list. Even if the ArrayList object is passed to the subroutine by value, the subroutine has access to its items:

Private Sub Button1 Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

Dim aList As New ArrayList()
PopulateList(aList)
Debug.WriteLine(aList(0).ToString)
Debug.WriteLine(aList(1).ToString)
Debug.WriteLine(aList(2).ToString)

End Sub

Sub PopulateList(ByVal list As ArrayList)

list.Add("1")
list.Add("2")
list.Add("3")

End Sub

The same is true for arrays and all other collections. Even if you specify the ByVal keyword, they're passed by reference. A more elegant method of modifying the members of a structure from within a procedure is to implement the procedure as a function returning a structure, as explained in the section "Functions Returning Structures," later in this chapter.

Table of Contents

     
 
W3computing.com Copyright 2011 © All Rights Reserved
 
  Home | Useful links | Contact us