Roman Koliada Roman Koliada - 3 years ago 199
C# Question

C# cast array to element type

I have a generic argument T which is an array in one particular case. Is it possible to cast array of objects to the array of

typeof(T).GetElementType()
? For example:

public TResult Execute<TResult>()// MyClass[] in this particular case
{
var myArray = new List<object>() { ... }; //actual type of those objects is MyClass
Type entityType = typeof(TResult).GetElementType(); //MyClass
//casting to myArray to array of entityType
TResult result = ...;
return result;
}

Answer Source

This is not a good idea. You have no way to constrain TResult to an array, so with your current code, someone could call Excute<int> and get a runtime exception, yuck!

But, why constrain to an array to begin with? Just let the generic parameter be the type of the element itself:

public TResult[] Execute<TResult>()
{
    var myArray = ... 
    return myArray.Cast<TResult>().ToArray();
}

UPDATE: In response to your comments:

If Execute is an interface method you can not change, then you can do the following:

public static TResult Execute<TResult>()
{
    var myArray = new List<object>() { ... };
    var entityType = typeof(TResult).GetElementType();
    var outputArray = Array.CreateInstance(entityType, myArray.Count);
    Array.Copy(myArray.ToArray(), outputArray, myArray.Count); //note, this will only work with reference conversions. If user defined cast operators are involved, this method will fail.
    return (TResult)(object)outputArray;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download