Recipe 8.16. Returning Arrays from Functions


Problem

You want to return an array from a function.

Solution

Sample code folder: Chapter 08\FunctionArrays

Declare the function to return an array of the desired type and do so in the function's Return statement.

Discussion

This recipe is very similar to Recipe 8.15, but the lesson is worth repeating: arrays of any type and size are easily passed to and returned from methods. The following example demonstrates a function that returns an array of 16 hexadecimal characters. The array is joined into a string and displayed for review in a message box, as shown in Figure 8-16:

 Dim result As New System.Text.StringBuilder result.Append("Hexadecimal characters: ") result.Append(String.Join(",", HexadecimalCharacters( ))) MsgBox(result.ToString( )) 

Figure 8-16. Returning an array of hexadecimal characters from a function


The HexadecimalCharacters( ) function includes a set of parentheses at the very end of the function declaration. This indicates that the function will return a string array and not just an ordinary string. The Return statement near the end of the function returns the string array hexChars( ):

 Public Function HexadecimalCharacters() As String( )    ' ----- Return the first 16 hex numbers as an array.    Dim hexChars(15) As String    For counter As Integer = 0 To 15       hexChars(counter) = Hex(counter)    Next counter    Return hexChars End Function 

See Also

Recipe 8.15 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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net