Reputation: 6131
I have looked, and it seems that my knowledge level is not sufficient to solve this problem. I am trying to make a method, that will do something on the objects which type is not known on the runtime. I do know that generics is a solution to my quest.
This is what I currently have and it works. Two different objects, but having same properties, so source properties are copied to destinaiton:
var source = dbContext.tbl_person.FirstOrDefault(item => item.PersonID == parameters.PersonID);
tbl_personHistory destination = new tbl_personHistory();
//Copy the properties
PropertyInfo[] destinationProperties = destination.GetType().GetProperties();
foreach (PropertyInfo destinationPi in destinationProperties)
{
PropertyInfo sourcePi = source.GetType().GetProperty(destinationPi.Name);
destinationPi.SetValue(destination, sourcePi.GetValue(source, null), null);
}
Then I tried to make this a method, so I can use it on many other places:
private static object CloneObjectProperties<T,T>(T source, T destination)
{
PropertyInfo[] destinationProperties = destination.GetType().GetProperties();
foreach (PropertyInfo destinationPi in destinationProperties)
{
PropertyInfo sourcePi = source.GetType().GetProperty(destinationPi.Name);
destinationPi.SetValue(destination, sourcePi.GetValue(source, null), null);
}
return destination;
}
How do I call this method, how Do I pass it source and destionation so it returns me object with copied properties.
I have tried this (and many more examples):
CloneObjectProperties((dynamic)source, (dynamic)destination);
But none of it works. Any insight is appreciated :)
Upvotes: 0
Views: 97
Reputation: 1263
Use different types for source and destination and it probably is also useful to change the return type to the destination type.
private static TDestination CloneObjectProperties<TSource, TDestination>(TSource source, TDestination destination)
{
PropertyInfo[] destinationProperties = destination.GetType().GetProperties();
foreach (PropertyInfo destinationPi in destinationProperties)
{
PropertyInfo sourcePi = source.GetType().GetProperty(destinationPi.Name);
destinationPi.SetValue(destination, sourcePi.GetValue(source, null), null);
}
return destination;
}
Since you don't use the source type you could change the method signature to:
private static TDestination CloneObjectProperties<TDestination>(object source, TDestination destination)
Upvotes: 1
Reputation: 136104
Surely you want source and destination to be different types?
private static object CloneObjectProperties<TSource,TDestination>(TSource source, TDestination destination)
And then you just call it as
CloneObjectProperties(source, destination);
Also: AutoMapper does this already!
Upvotes: 1