ConvertTo<T>

public static T[] ConvertTo<T>(this Array ar) {
    T[] ret = new T[ar.Length];
    System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
    if (tc.CanConvertFrom(ar.GetValue(0).GetType())) {
        for (int i = 0; i < ar.Length; i++) {
            ret[i] = (T) tc.ConvertFrom(ar.GetValue(i));
        }
    }
    else {
        tc = System.ComponentModel.TypeDescriptor.GetConverter(ar.GetValue(0).GetType());
        if (tc.CanConvertTo(typeof(T))) {
            for (int i = 0; i < ar.Length; i++) {
                ret[i] = (T) tc.ConvertTo(ar.GetValue(i), typeof(T));
            }
        }
        else {
            throw new NotSupportedException();
        }
    }
    return ret;
}
Example:
int[] ipParts = Request.UserHostAddress.Split('.').ConvertTo<int>();

Description

Converts an Array of arbitrary type to an array of type T. If a suitable converter cannot be found to do the conversion, a NotSupportedException is thrown.

Details

Double click on the code to select all.

 

;