Sunday, April 1, 2012

Mixed Data Types in .NET Arrays

The first thing we learn about arrays is that we declare them as an array of a specific type. Consider the following examples:


The data type for the elements of an array variable is explicitly determined during design-time. Any attempt to assign a string in boolArray element will result in a compile error. To be able to have an array with multiple data types for the elements, we can use ArrayLists. But we can use the basic arrays to store different data types in the elements. We simply declare the variable as an array of objects.



Running this as a console application gives us the below output...

System.String
System.Int32
System.Guid

... showing that the elements are indeed stored as the assigned values' types.

Of course, just because this is possible with arrays doesn't mean we should be doing it just because. Declaring variables as objects should be avoided whenever possible. But there is a place for object arrays in the right circumstances.

To quote another blog who described it really well, "...an ArrayList is simply a collection class - one that supports the IList interface - whose internal memory structure is an array. The keyword here, however, is internal. The ArrayList is not an array." [1]

This means that if we know the size of the array ahead of time, we're better off using object arrays than an ArrayList to avoid the overhead of the internal implementations of the IList interface in the latter. Also, since internally it is an array, adding elements into an ArrayList also involves creating a new array with additional elements, and then copying the old array elements into it.

Just a few things worth considering during design.


[1] Array vs ArrayList by Lycangeek

No comments:

Post a Comment