In addition to returning custom data types, VB 2008 functions can also return arrays. This is an interesting possibility that allows you to write functions that return not only multiple values, but also an unknown number of values.
In this section, we’ll write the Statistics() function, similar to the CalculateStatistics() function you saw a little earlier in this chapter. The Statistics() function returns the statistics in an array. Moreover, it returns not only the average and the standard deviation, but the minimum and maximum values in the data set as well. One way to declare a function that calculates all the statistics is as follows:
Function Statistics(ByRef DataArray() As Double) As Double()Code language: VB.NET (vbnet)
This function accepts an array with the data values and returns an array of Doubles. To implement a function that returns an array, you must do the following:
1. Specify a type for the function’s return value and add a pair of parentheses after the type’s name. Don’t specify the dimensions of the array to be returned here; the array will be declared formally in the function.
2. In the function’s code, declare an array of the same type and specify its dimensions. If the function should return four values, use a declaration like this one:
Dim Results(3) As DoubleCode language: VB.NET (vbnet)
The Results array, which will be used to store the results, must be of the same type as the function— its name can be anything.
3. To return the Results array, simply use it as an argument to the Return statement:
Return(Results)Code language: VB.NET (vbnet)
4. In the calling procedure, you must declare an array of the same type without dimensions:
Dim Statistics() As DoubleCode language: VB.NET (vbnet)
5. Finally, you must call the function and assign its return value to this array:
Stats() = Statistics(DataSet())Code language: VB.NET (vbnet)
Here, DataSet is an array with the values whose basic statistics will be calculated by the Statistics() function. Your code can then retrieve each element of the array with an index value as usual.