Take the 2-minute tour ×

I have the following class structure (pseudocode):

Class A
  Property string Who;
  Property string Where;

Class B
  Property A Information;

Class C
   Property String Who;

I am trying to find out how to set set B.A.Who = C.Who using reflection in .NET 4.0.


share|improve this question

1 Answer 1

up vote 3 down vote accepted

Well, this isn't all that difficult to do sort of correctly, but it would get really messy if you wanted argument-validation, graceful error-handling etc. Here's an example that should highlight the technique (no checks):

static void SetBsAsWhoToCsWho(object b, object c)
    // csWho = c.Who
    object csWho = c.GetType().GetProperty("Who").GetValue(c, null);

    // a = b.Information
    object a = b.GetType().GetProperty("Information").GetValue(b, null);

    // a.Who = csWho
    a.GetType().GetProperty("Who").SetValue(a, csWho, null);

You need all sorts of checks in the above code to make it robust. It would really help if you could tell us why you want to use reflection to accomplish this task. Depending on the scenario, there may be solutions that are more appropriate, such as:

  1. The obvious type-safe code.
  2. Casting as necessary, followed by type-safe code.
  3. Generating a delegate by constructing and compiling an expression-tree.
  4. The use of dynamic.
  5. AutoMapper and other libraries.
share|improve this answer

Your Answer


