I am trying to set an array field using reflection like this:
FieldInfo field = ...
A[] someArray = GetElementsInSomeWay();
field.SetValue(this, someArray);
The field has type B[]. B inherits from A and the exact type of B is not known at compile time.
GetElementsInSomeWay() returns A[] but the real elements inside are all B's. GetElementsInSomeWay() is a library method and can't be changed.
What I can do at most is to get the B with System.Type type = field.FieldType.GetElementType().
However I can't cast the array to the required type, e.g.
someArray as type[] because [] requires an exact type before it to declare an array type. Or am I missing something here? Can I declare an array of some type, if the type becomes known in runtime using System.Type variable?
Doing it the direct way produces the following error (here A is UnityEngine.Component and B is AbilityResult which can also be one of a few dozens other classes, all inheriting (possibly thru a long inheritance chain) from UnityEngine.Component):
ArgumentException: Object type UnityEngine.Component[] cannot be converted to target type: AbilityResult[]
Parameter name: val
System.Reflection.MonoField.SetValue (System.Object obj, System.Object val, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Globalization.CultureInfo culture) (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System.Reflection/MonoField.cs:133)
System.Reflection.FieldInfo.SetValue (System.Object obj, System.Object value) (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System.Reflection/FieldInfo.cs:150)