2

Is it possible to convert an object[] to a value type such as double[] when the value type is only known at runtime? An exception is perfectly acceptable if an object in object[] cannot be converted to the value element type (say double) using the .net built-in conversions.

var original = new object[] { 1 , 2 , 3 , 4 , 5 , 6 }
Type resultType = typeof( double[] ); // or any means of getting a type at runtime
var result = ??

The following attempts have failed:

# error: Object must impliment IConvertible
Convert.ChangeType( original , resultType );

# error: Object cannot be stored in an array of this type.
var result = Array.CreateInstance( resultType , original.Length );
for ( int i = 0 ; i < original.Length ; i++ )
{
    result.SetValue( Convert.ChangeType( original[ i ] , resultType.GetElementType() ) , i );
}
Suraj
  • 35,905
  • 47
  • 139
  • 250
  • Really, why not just making a double array and casing each object to double and set it into it's index? Simple for loop? Can add "if (obj is double){...}" to handle a bad array of objects. – SimpleVar Apr 21 '12 at 02:57
  • resultType is not guaranteed to be double. Its determined at runtime. It could be any value type. – Suraj Apr 21 '12 at 03:10
  • Why not using the generic Cast extension method? If you want to constraint to ValueTypes you can make your own Cast method that uses the extension Cast method but throws if "!typeof(T).IsValueType". Take a look at my answer. – SimpleVar Apr 21 '12 at 03:36
  • could you show a full working example? I think its difficult to use a generic function with a Type determined at runtime. See http://stackoverflow.com/questions/326285/deciding-on-type-in-the-runtime-and-applying-it-in-generic-type-how-can-i-do-t and http://stackoverflow.com/questions/234008/is-it-impossible-to-use-generics-dynamically – Suraj Apr 21 '12 at 14:34

2 Answers2

4

Your last attempt was very close: the first line should be

var result = Array.CreateInstance(resultType.GetElementType(), original.Length);

because Array.CreateInstance takes element type as its first parameter. Other than that, it should work perfectly.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
private T[] Cast<T>(params object[] items)
{
    if (!typeof(T).IsValueType)
    {
        throw new ArgumentException("Destined type must be Value Type");
    }

    return items.Cast<T>().ToArray();
}
SimpleVar
  • 14,044
  • 4
  • 38
  • 60
  • upvoted to cancel the downvote. Though OP wasnt very clear about it, he says in code comments that type object may be available during runtime only. – nawfal Jan 17 '14 at 14:35