Search code examples
c#arraysprimitive-types

Given an unknown primitive type array in the form of an object, convert it to double array C#


I have searched previous questions here, but nothing quite answers exactly what I am looking for.

I am retrieving an array of primitive type via reflection using PropertyInfo in the form of type object.

    Type t = typeof(MyType);    
    PropertyInfo pi = t.GetProperty("Property Name");

    object primitiveTypeArray = pi.GetValue(myObject)

    double[] convertedArray = (double[])primitiveTypeArray; 

There are only 3 type this array can be (for now), double, float or ulong. This assignment of convertedArray will only work if the primitiveTypeArray object contains a double[], but fails if it is a float[] of ulong[].

I have found the Array class and Convert class have some helper functions that might assist, but I am having trouble understanding how to appropriately use them to solve this problem.

Thank you


Solution

  • If you have just 3 types, why not to check all these possibilities?

    using System.Linq;
    
    ...
    
    object primitiveTypeArray = pi.GetValue(myObject)
    
    double[] convertedArray = 
        primitiveTypeArray is double[] da ? da
      : primitiveTypeArray is float[] fa ? fa.Select(item => (double) item).ToArray()
      : primitiveTypeArray is ulong[] ua ? ua.Select(item => (double) item).ToArray()
      : null; // or throw exception here
    

    Please, note that we can't just cast float[] into double[] but can create required double[].