Before all, I know about AutoMapper, and I don't want to use it. Because I'm learning C# and I want to receive a deep view of it. So I'm trying to do this issue (explained below) myself.
However, I'm trying to create a property copier to cope values of one type's properties to another one, if the property has the same name and type and is readable from source and writable in target. I'm using type.GetProperties()
method. Sampled method is here:
static void Transfer(object source, object target) {
var sourceType = source.GetType();
var targetType = target.GetType();
var sourceProps = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var targetProps = (from t in targetType.GetProperties()
where t.CanWrite
&& (t.GetSetMethod().Attributes & MethodAttributes.Static) == 0
select t).ToList();
foreach(var prop in sourceProps) {
var value = prop.GetValue(source, null);
var tProp = targetProps
.FirstOrDefault(p => p.Name == prop.Name &&
p.PropertyType.IsAssignableFrom(prop.PropertyType));
if(tProp != null)
tProp.SetValue(target, value, null);
}
}
It works, but I read an answer at SO, that using System.Reflection.Emit
and ILGenerator
and late-bound delegates are more quickly and have a higher performance. But there was not more explanation or any link. Can you help me to understanding ways to speed up this code? or can you suggest me some links about Emit
, ILGenerator
, and late-bound delegates please? Or anything you think will help me to subject?
COMPELETE Q:
I understand and learn many things from @svick's answer. But now, if I want to use it as an open generic method, how can I do it? something like this:
public TTarget Transfer<TSource, TTarget>(TSource source) where TTarget : class, new() { }
or an extension:
public static TTarget Transfer<TSource, TTarget>(this TSource source) where TTarget : class, new() { }