5

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?

1
  • 1
    All the provided answers are working fine; accepted the @AlexWiese version as correct answer as he provided such solution before AnyName. Thanks to all of you guys! Commented Feb 25, 2017 at 12:33

3 Answers 3

4

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();
Sign up to request clarification or add additional context in comments.

Comments

3

If you don't know the type of array elements at compile-time:

var doubleArray = (objArray as Array).OfType<object>()
    .Select(m => Convert.ToDouble(m)).ToArray();

3 Comments

Yes, unfortunately the library method returns an object and not an object[], so Select does not apply.
@Nkosi I didn't notice that. I've just updated my answer.
@AnyName, nice way but you actually convert to int at compile time, while I am just able to read the underlying type at runtime with a GetType(). Maybe my example is not 100% clear, I will try to edit it so that it is clearer
1

u can create extension method..

        public static IEnumerable<T> Convert<T>(this IEnumerable source)
        {
           foreach (var item in source)
               yield return (T)System.Convert.ChangeType(item, typeof(T));
        }

using ..

        object objArray;
        GetChannelData("test", out objArray);
        var array = (IEnumerable)objArray;
        var doubleArray = array.Convert<double>().ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.