1

I could use a bit of relection help. I am passing an object into the constructor of another object. I need to loop through the parameter's properties and set the new objects properties based on it. Most, but not all, of the params properties exist in the new object.

I have this so far, the basic skeleton.

  public DisabilityPaymentAddEntity(DisabilityPaymentPreDisplayEntity preDisplay)
  {
      Init(preDisplay);
  }

  private void Init(DisabilityPaymentPreDisplayEntity display)
  {
       //need some type of loop using reflection here
  }

In the 'Init' method, I need to loop through 'display's properties and set any of 'DisabilityPaymentAddEntity' properties of the same name to values in the preDisplay.

Can anyone give me a clue what I need to do? I am sure I need to use PropertyInfo etc..

Thanks, ~ck in San Diego

Hcabnettek
  • 12,678
  • 38
  • 124
  • 190
  • 1
    Can you explain further why you need to use reflection? Actually, this sounds like a job for Automapper : http://www.codeplex.com/AutoMapper – Jay Jan 26 '10 at 21:15
  • HI Jay, Im going to give this a try. Is it fairly easy to use? I downloaded the samples and will check it out. Thanks. – Hcabnettek Jan 26 '10 at 22:01
  • Wow that Automapper worked like a champ!!! One question tho, where do I create the Map? In the examples I see online they suggest global.asax. I try to keep thing neat and tidy, and I will be using this DLL outside of my web application. Where do I set up a map inside a class library? Thanks! – Hcabnettek Jan 26 '10 at 22:34

1 Answers1

3

Something like this I think

Type target = typeof(DisabilityPaymentAddEntity);
foreach(PropertyInfo pi in display.GetType().GetProperties())
{
     PropertyInfo targetProp = target.GetProperty(pi.Name);
     if(targetProp!=null)
     {
        targetProp.SetValue(this, pi.GetValue(display, null), null);
     }
}
Gregoire
  • 24,219
  • 6
  • 46
  • 73