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>()orMethod<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
This seems to do what you are asking...
You'll need
Then this method to do the job.
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.