Reputation: 36557
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 );
}
Upvotes: 2
Views: 1124
Reputation: 14522
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();
}
Upvotes: 0
Reputation: 726699
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.
Upvotes: 4