Link to home
Start Free TrialLog in
Avatar of wint100
wint100Flag for United Kingdom of Great Britain and Northern Ireland

asked on

For Loop to populate class with same property names

I have 2 classes with properties mostly of the same name. I have a List<Type1> and need to use a for loop to populate a List<Type2>. There are 50+ properties to set so to avoid having a lot of code to say:

foreach (var b in List1)
{
var c = new Type2
c.P1=b.P1
c.P2=b.P2
etc..
}

Is there a way to set properties where the property name is the same?

There a re a couple of additional properties in Type2 but I can set these manually.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wint100

ASKER

This looks ideal. I do get one complier error though for the p.GetValue(source), it seems to need more args:

Error      351      No overload for method 'GetValue' takes 1 arguments
Which version of .Net are you targeting?
Avatar of wint100

ASKER

Currently 4.0
Ah, in that case you'll need to change it to:
p.GetValue(source, null)

Open in new window

Why not create a "copy" constructor that you can simply pass an existing instance to?

e.g.

public class Type2
{
    public Type2(Type1 original)
    {
        this.P1 = original.P1;
        this.P2 = original.P2;
        etc...
    }
}

Open in new window


True, you still have to flesh out all of the property assignments, but you're doing so only in one place. Now whenever you require a duplication you simply construct a new object:

e.g.

foreach (var b in List1)
{
    var c = new Type2(b);
}

Open in new window


Reflection is an expensive operation that is generally best used when you don't have another alternative.
Avatar of wint100

ASKER

Interesting, I have implemented Carl's emthod and is done seem to work. I'm trying to avoid typing out 120 properties and having to remember to change the code when I change the class.
There's nothing truly evil about Reflection...it's just expensive since it's not done at compile time. If it solves your need, then all should be good. But if you start noticing adverse performance issues, the Reflection bit should be kept in mind as a source of the problem.