Setting a field on an object that is a property in a class using reflection in .NET -


i have following class structure (pseudocode):

class {   property string who;   property string where; }  class b {   property information; }  class c {    property string who; } 

i trying find out how set set b.a.who = c.who using reflection in .net 4.0.

thanks!

well, isn't difficult sort of correctly, messy if wanted argument-validation, graceful error-handling etc. here's example should highlight technique (no checks):

static void setbsaswhotocswho(object b, object c) {     // cswho = c.who     object cswho = c.gettype().getproperty("who").getvalue(c, null);      // = b.information     object = b.gettype().getproperty("information").getvalue(b, null);      // a.who = cswho     a.gettype().getproperty("who").setvalue(a, cswho, null); } 

you need sorts of checks in above code make robust. if tell why want use reflection accomplish task. depending on scenario, there may solutions more appropriate, such as:

  1. the obvious type-safe code.
  2. casting necessary, followed type-safe code.
  3. generating delegate constructing , compiling expression-tree.
  4. the use of dynamic.
  5. automapper , other libraries.

Comments