Suppose I have two classes:
public class Student
{
public int Id {get; set;}
public string Name {get; set;}
public IList<Course> Courses{ get; set;}
}
public class StudentDTO
{
public int Id {get; set;}
public string Name {get; set;}
public IList<CourseDTO> Courses{ get; set;}
}
I would like to copy value from Student class to StudentDTO class:
var student = new Student();
StudentDTO studentDTO = student;
How can I do that by reflection or other solution?
The lists make it tricky... my earlier reply (below) only applies to like-for-like properties (not the lists). I suspect you might just have to write and maintain code:
edit; only applies to shallow copies - not lists
Reflection is an option, but slow. In 3.5 you can build this into a compiled bit of code with
Expression
. Jon Skeet has a pre-rolled sample of this in MiscUtil - just use as:Because this uses a compiled
Expression
it will vastly out-perform reflection.If you don't have 3.5, then use reflection or ComponentModel. If you use ComponentModel, you can at least use
HyperDescriptor
to get it nearly as quick asExpression
Write a implicit operator in anyone class
now you can do that
FYI
When I was having the same question I found AutoMapper (http://automapper.codeplex.com/) Then after reading AboutDev's answer i was done some simple test, the results pretty impressive
here the test results:
Test Auto Mapper:22322 ms
Test Implicit Operator:310 ms
Test Property Copy:250 ms
Test Emit Mapper:281 ms
And i would like to underline that it is sample only with classes(StudentDTO, Student) which have only a couple of properties, but what would happened if classes would have 50 - 100 properties, i guess it will affect performance dramatically.
More tests details here: Object copy approaches in .net: Auto Mapper, Emit Mapper, Implicit Operation, Property Copy
Ok I just looked up the MiscUtil that Marc posted about and its just awesome. I hope mark doesn't mind me adding the code here.
There's a library for doing just that - http://emitmapper.codeplex.com/
It's much faster than AutoMapper, it uses System.Reflection.Emit, so the code runs almost as fast as if it was hand-written.