ChangeType from string[] to T[] which can be nullable (int..)

74 views Asked by At

I've seen a lot of solutions but only for particular cases such as:

  • T != int;
  • T is to be set by the user e.g. Method<int>() or Method<string>()...

But I know the type only at runtime, so the above bullet points do not stand. I need to be the most generic possible. Here's the code so far:

Type typ = GetTheType(); // the type in which I want to convert those strings. It can be int, double, or whatever
string[] array = GetArrayOfStrings(); // I get the array from somwhere
var arrayConverted = array.Select(p => Convert.ChangeType(p, typ)).ToArray(); // I tested the code with typ=int32 and arrayConverted is of type object[]

arrayConverted happens to be of type object[] instead of int[] as I tested it with. Any idea?

EDIT:

The bullet points represent already known solutions, I need a generic one, where I don't know the type untile runtime

1

There are 1 answers

5
Kevin On

This seems to do what you are asking...

You'll need

using System;
using System.ComponentModel;

Then this method to do the job.

    public T[] ConvertStringArray<T>(string[] data)
    {
        var returnData = (T[])Array.CreateInstance(typeof(T),data.Length);
        var i = 0;
        foreach(var item in data)
        {
            returnData[i] = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(item);
            i++;
        }
        return returnData;
    }

Just to point out - if one or more of the strings passed in the array are not convertable to type T, this will throw a conversion exception.