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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With