Cast Object[] to Type[] via Reflection
-
13-12-2019 - |
Question
Goal
I have an object[]Source,object Target, and FieldInfo Var (Var.FieldType.IsArray is true). I want to run Var.SetValue(Target,Source). However, I cannot convert "object[]" -> "anotherType[]"
Sample Run
object[]Source=new object[2]{"Hello","World"};
Var.SetValue(Target,Source); //Cannot Convert "object[]"->"string[]"
[note: I want to be able to use ints, doubles, floats, etc. Otherwise, this problem would be trivially easy]
Research
Use Var: Cannot use because cannot create var arrays
Use Generics:
This works for
myField.SetValue(target,GenericCastArray<string>(source));
However, it does not work for
Type someType=typeof(string); //or int, or float
(myfield.SetValue(target,GenericCastArray< someType > (source))
* http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/fe14d396-bc35-4f98-851d-ce3c8663cd79/* returns null reference exception, I think at this.GetType()
EDIT: Meh Solution Based on the comments, it is impossible to convert from object[] to string[]. However, the following code works adequately well.
object[]Source=null;
Type basetype=Var.FieldType.GetElementType();
int l=somelength;
if (basetype.IsEquivalentTo(typeof(string))) Source = new string[l];
//repeat for all types
source=//run your Reflection here
var.SetValue(target,source);
Solution
It is not possible to cast Array of one type to Array of another type (i.e. object[]
to string[]
) because these are different non compatible types. Reflection will not help to cast either.
To convert you will always need to create some sort of copy of the array either directly or by creating IEnumerable<DestinationType>
via one of LINQ conversion functions.