title: C# FieldInfo.SetValue with an array parameter and arbitrary element type
body: <p>I am trying to set an array field using reflection like this:</p>
  
  <pre><code>FieldInfo field = ...
  A[] someArray = GetElementsInSomeWay();
  field.SetValue(this, someArray);
  </code></pre>
  
  <p>The field has type <code>B[]</code>. <code>B</code> inherits from <code>A</code> and the exact type of <code>B</code> is not known at compile time. 
  <code>GetElementsInSomeWay()</code> returns <code>A[]</code> but the real elements inside are all <code>B</code>'s. <code>GetElementsInSomeWay()</code> is a library method and can't be changed.</p>
  
  <p>What I can do at most is to get the <code>B</code> with <code>System.Type type = field.FieldType.GetElementType()</code>.
  However I can't cast the array to the required type, e.g. 
  <code>someArray as type[]</code> because <code>[]</code> 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 <code>System.Type</code> variable?</p>
  
  <p>Doing it the direct way produces the following error (here <code>A</code> is <code>UnityEngine.Component</code> and <code>B</code> is <code>AbilityResult</code> which can also be one of a few dozens other classes, all inheriting (possibly thru a long inheritance chain) from <code>UnityEngine.Component</code>):</p>
  
  <pre><code>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)
  </code></pre>