Export (0) Print
Expand All

How to: Create an Array with Mixed Element Types

You declare only one data type for an array, and all its elements must be of that data type. Normally this limitation is desirable, since all the elements are closely related to each other and have similar types of values. However, sometimes the elements are not closely related or do not have similar values. In this case, you can declare the array elements to be of the Object Data Type, and the individual elements can point to different kinds of data, such as numbers, characters, strings, objects, and other arrays.

To create an array with elements of different data types

  • Declare the array as Object. The following example declares a variable to hold an array of Object elements, creates the array, and assigns it to the variable.

    Dim mixedTypes As Object() = New Object() {}
    

    When you use the Object data type, keep in mind that the performance is not as efficient as when you use a more specific data type. This is because the runtime has to convert the data between its natural data type and Object, using operations called boxing and unboxing. This additional processing can hurt your performance if you do it often.

To access elements of different data types in an array

  • Read or write the elements in the normal way. You can store and retrieve an element of any data type in an Object array.

    The following example demonstrates putting information of different data types in an Object array. It stores employee information in the array in variable employeeData.

    Dim employeeData(3) As Object
    employeeData(0) = "Alex Hankin"
    employeeData(1) = "4242 Maple Street"
    employeeData(2) = 48
    employeeData(3) = #8/23/1956#
    

    To retrieve information of different data types from an Object array, you can convert an element to the appropriate data type, as the following example illustrates.

    Dim age As Integer = CInt(employeeData(2))
    Dim birthDate as Date = CDate(employeeData(3))
    

In a situation where the elements are not similar or related to each other, another possibility is to put them in a collection instead of an Object array. For more information, see Collections as an Alternative to Arrays.

Community Additions

ADD
Show:
© 2014 Microsoft