Advanced Features of Arrays
You can assign the contents of one array to another, create functions that accept and return arrays, and create properties that accept and return arrays. In many cases these techniques can improve the performance of your application.
Since arrays are objects, they can be used in assignment statements like other object types. When assigning one array to another, the following rules apply:
- The rank (number of dimensions) of the destination array must be the same as that of the source array.
- Provided the ranks of the two arrays are equal, the dimensions do not need to be equal. The number of elements in a given dimension can change during assignment.
- Either both arrays must have reference type elements or both arrays must have value type elements.
- If both arrays have value type elements, the element data types must be exactly the same.
- If both arrays have reference type elements, there must be a widening conversion from the source element type to the destination element type.
The compiler reports an error if the above rules are violated, for example if a data type cannot be coerced or the ranks are unequal. You can add error handling to your code to make sure that the arrays are compatible before attempting an assignment.
Returning an Array from a Function
A function can return an array of values. For example, you might want to return a Byte array without having to perform conversions to and from a string. In the following example, the Function procedure
ArrayFunction returns an array of bytes.
Dim B As Byte = CByte(54) ' Seed value for ArrayFunction argument. Dim I As Integer ' Loop counter for displaying returned values. Dim ReturnArray() As Byte ' To be set from ArrayFunction return. ReturnArray = ArrayFunction(B) For I = 0 To ReturnArray.GetUpperBound(0) ' Highest subscript. Debug.WriteLine("Byte " & I & ": " & ReturnArray(I)) Next I ' ... Public Function ArrayFunction(ByVal B As Byte) As Byte() Dim X(2) As Byte ' Allocates three elements. X(0) = B X(1) = B + B X(2) = B + CByte(200) Return X End Function
After running the preceding example,
ReturnArray points to a three-element array containing the element values assigned to the array
ArrayFunction. In this example,
ReturnArray must have the same element type as the function return because it is a value type (in this case Byte). If the element types of
ArrayFunction had been reference types, a widening conversion would have been acceptable.
Byte Data Type | Arrays Overview | Array Usage | Declaring Array Variables | Arrays of Arrays | Collections as an Alternative to Arrays | Value Types and Reference Types | Widening and Narrowing Conversions | Array Conversions