title: runtime casting of an object[] to a custom type array
body: <p>I am making a tool for defining objects in WPF so they can be serialized into JSON for testing our REST service. It uses reflection to pull all the properties into the GUI, and generates a JSON based on the input. This works fantastically for everything except properties that are arrays of types that I defined. I am using the <code>object.InvokeMember()</code> method to accomplish this.</p>
  
  <p>The problem is, you have to pass it an object array as the parameter. When its just one thing, its fine, but when its an array, it throws an exception because the object array isn't casted to the type the property is. This is hard to explain.</p>
  
  <p>some code:</p>
  
  <pre><code>private void Button_Click(object sender, RoutedEventArgs e)
  {
      object obj = new MyType();
      List&lt;list&lt;object&gt;&gt; list = new List&lt;List&lt;object&gt;&gt;();
      object[] ob = new object[] { list.ToArray() };
      obj.GetType().InvokeMember(
          "MyOtherTypes",
          BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
          Type.DefaultBinder,
          obj,
          ob);
      UpdateJson(obj);
  }
  
  public class MyType
  {
      public MyOtherType[] MyOtherTypes { get; set; }
  }
  
  public class MyOtherType
  {
      public int SomeProperty { get; set; }
  }
  </code></pre>
  
  <p>I am sure whoever reads this will be confused, so please ask questions.</p>
  
  <p>More code, an example of modifying a type that is not an array. This part works fine:</p>
  
  <pre><code>object[] ob = new object[] { obj };
  obj.GetType().InvokeMember(
      "SomePropertyThatIsNotAnArray", 
      BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
      Type.DefaultBinder, 
      obj, 
      ob);
  UpdateJson(obj);
  </code></pre>
  
  <p>Been trying something like this, but same deal, cant cast object[] to MyType[]</p>
  
  <pre><code>MethodInfo castMethod = this.GetType().GetMethod("Cast").MakeGenericMethod(
      obj.GetType().MakeArrayType());
  object castedObject = castMethod.Invoke(
      null, 
      new object[] { list[someIndex].ToArray() });
  obj.GetType().InvokeMember(
      "SomePropertyThatIsNotAnArray",
      BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
      Type.DefaultBinder, 
      obj, 
      castedObject);
  
  public static T Cast&lt;T&gt;(object o)
  {
      return (T)o;
  }
  </code></pre>