Recipe 8.15. Passing Arrays to Methods


You want to pass and return arrays to and from methods as easily as other simple variable types.


Sample code folder: Chapter 08\ArrayParameters

Unlike Visual Basic 6.0, in Visual Basic 2005 it's easy to pass and return any type of object, including arrays.


The following code provides a fun example by passing a string array to a function that returns an even bigger string array. The names of the four card suits are placed in a small string array. This array is passed to FillDeckOfCards(), which creates and returns a string array containing the names of all the cards in a deck:

 Dim result As New System.Text.StringBuilder Dim suits( ) As String = {"Spades", "Hearts", "Diamonds", "Clubs"} Dim cardDeck( ) As String = FillDeckOfCards(suits) Shuffle(cardDeck) For counter As Integer = 0 To 6     result.AppendLine(cardDeck(counter)) Next counter MsgBox(result.ToString( )) 

The Shuffle() method (designed in Recipe 8.5) shuffles the returned array, and the first seven cards in the array are displayed for review, as shown in Figure 8-15. Of course, your results will vary based on the state of your random number generator.

Figure 8-15. Passing and returning arrays

The FillDeckOfCards( ) function is passed a string array and returns one, too:

 Public Function FillDeckOfCards(ByVal suit As String()) As String( )     Dim deck(51) As String     Dim cardNumber As Integer     Dim suitNumber As Integer     For counter As Integer = 0 To 51         cardNumber = counter Mod 13         suitNumber = counter \ 13         Select Case cardNumber             Case 0                 deck(counter) = "Ace of "             Case 10                 deck(counter) = "Jack of "             Case 11                 deck(counter) = "Queen of "             Case 12                 deck(counter) = "King of "             Case Else                 deck(counter) = cardNumber.ToString & " of "         End Select         deck(counter) &= suit(suitNumber)     Next counter     Return deck End Function 

You may pass and return objects in Visual Basic 2005, a process similar to using Variants in Visual Basic 6.0. But in general, it is better to pass and return explicitly typed arrays, as in the example presented here. This prevents the runtime overhead required for constantly converting variable types, and it helps the compiler determine at compile time if you're attempting to pass incompatible data. In general, consider overloaded methods and generics as two ways to enhance the flexibility of methods, while optimizing the compile- and runtime operations.

See Also

Recipe 8.16 discusses similar functionality.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: