title: Access fields of a Struct in an Object with Reflection
body: <p>I'm trying to use reflection (ultimately on unknown at compile time) <code>object</code> which include <code>struct</code>. I've got as far as <code>TypedReference.MakeTypedReference</code> but I've hit a wall.</p>
  
  <p>Here's my Class and Struct</p>
  
  <pre><code>public class MyObject
  {
      public int Id;
      public Money Amount; 
  }
  
  public struct Money
  {
      public int Vaule;
      public string Code;
  }
  </code></pre>
  
  <p>And here is how I am trying to set "Code" of "Amount" in MyObject using reflection. As I mention above, I'm looking for a solution which does not know about these types at compile time (that would be too easy!)</p>
  
  <p>Here's the code I have so far (I've used [0], [1] to make the code simpler)</p>
  
  <pre><code>var obj = new MyObject() { Id = 1 };
  obj.Amount.Vaule = 10;
  obj.Amount.Code = "ABC";
  
  FieldInfo[] objFields = obj.GetType().GetFields();
  FieldInfo[] moneyFields = objFields[1].GetValue(obj).GetType().GetFields();
  
  List&lt;FieldInfo&gt; fields = new List&lt;FieldInfo&gt;() { objFields[1] };
  fields.AddRange( moneyFields );
  
  TypedReference typeRef = TypedReference.MakeTypedReference( 
                             objFields[1].GetValue( obj ), fields.ToArray() );
  
  moneyFields[1].SetValueDirect( typeRef, "XXX" );
  </code></pre>
  
  <p>The TypedReference.MakeTypedReference blows up with; "FieldInfo does not match the target Type." Likewise if I just pass <code>objFields[1]</code>. And if pass just <code>moneyFields</code> I get "TypedReferences cannot be redefined as primitives."</p>
  
  <p><strong>Why?</strong> Let's say I'm creating Random test fixtures and want to populate class fields with random data :)</p>