This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 2.0+

Converting an Entire Array to a New Type

Sometimes you will want to convert the contents of an entire array from one type to another. Using the .NET framework 2.0, generics and delegates, this process can be achieved without the requirement to manually create looping structures.

ConvertAll Method

In the .NET framework version 2.0, Microsoft added a generic method named ConvertAll to the Array class. This method allows an entire array to be converted from one data type to another. The method creates a new array, loops through the existing array and executes a delegate for each element. The resultant value from the delegate is stored in the new array, which becomes the method's return value.

The syntax for the ConvertAll method is as follows:

result = Array.ConvertAll<input-type, output-type>(input-array, converter);

The four changeable elements in the syntax are:

  • input-type. The type of the items held in the input array.
  • output-type. The type of the items to be created in the returned array.
  • input-array. The array to duplicate and convert. This must be a one-dimensional, zero-based array.
  • converter. A delegate containing the code to use to convert each of the items in the array. This may be as simple as a cast operation or be much more complicated, perhaps converting each numeric value to its English text equivalent as a string. The delegate must accept a parameter of the input data type and return a result of the output data type.

The converter delegate will be executed once for each element in the input array. The delegate may be declared separately or can be provided as an anonymous method, as in the examples below.

Simple Conversion Example

The following example performs a simple cast for each element of an integer array. The resultant array contains long integer values.

int[] integerArray = new int[] { 1, 2, 3, 4, 5 };

long[] longArray = Array.ConvertAll<int, long>(integerArray, delegate(int i)
    return (long)i;

More Complex Conversion Example

The second example converts an array of integer values into an array of strings. In this case, the outputted strings contain the original number followed by a series of X characters. The number of X's matches the integer from the input array.

int[] integerArray = new int[] { 1, 2, 3, 4, 5 };

string[] stringArray = Array.ConvertAll<int, string>(integerArray, delegate(int i)
    return string.Format("{0} {1}", i, new string('X', i));
22 June 2008