Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# converting an array returned as a generic object to a different underlying type

I have a C# method which uses object as a generic container to return a data array which could be declared using different data types. Below a simplified example of such a method:

void GetChannelData(string name, out object data)
{
    // Depending on "name", the underlying type of  
    // "data" can be different: int[], byte[], float[]...
    // Below I simply return int[] for the sake of example
    int[] intArray = { 0, 1, 2, 3, 4, 5 };
    data = intArray;
}

I need to convert all the returned array elements to double but so far I could not find a way. Ideally I would like to perform something like:

object objArray;
GetChannelData("test", out objArray);
double[] doubleArray = Array.ConvertAll<objArray.GetType().GetElementType(), double>(objArray, item => (double)item);

Which miserably fails because ConvertAll does not accept types defined at runtime. I have also tried intermediate conversions to a dynamic variable, to no avail.

Is there any way to perform such type conversion in a simple manner?

like image 747
Metal76 Avatar asked Feb 25 '17 11:02

Metal76


1 Answers

If you don't know the type at compile time you can try to convert it.

var array = (IEnumerable)objArray;
var doubles = array.OfType<object>().Select(a => Convert.ToDouble(a)).ToArray();
like image 184
Alex Wiese Avatar answered Sep 28 '22 05:09

Alex Wiese