wint100
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Which version of .Net are you targeting?
ASKER
Currently 4.0
Ah, in that case you'll need to change it to:
p.GetValue(source, null)
Why not create a "copy" constructor that you can simply pass an existing instance to?
e.g.
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.
Reflection is an expensive operation that is generally best used when you don't have another alternative.
e.g.
public class Type2
{
public Type2(Type1 original)
{
this.P1 = original.P1;
this.P2 = original.P2;
etc...
}
}
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);
}
Reflection is an expensive operation that is generally best used when you don't have another alternative.
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.
ASKER
Error 351 No overload for method 'GetValue' takes 1 arguments