C# coding tip: copying object property values from object to another
Posted: (EET/GMT+2)
I recently was developing an ASP.NET MVC application and working with the view models and models of the application. In this project, I found myself needing a quick solution to copy public property values from database model objects to view model objects. Copy-paste of course works, but it tedious and error-prone.
Of course, the answer in the .NET land would be to use reflection. Here's the implementation I've been using (without exception handling):
using System.Reflection;
...
public static class MyCopier
{
// copies public property values from one object to another
public static void CopyObjectProperties(
object source, object destination)
{
PropertyInfo[] sourceProperties =
source.GetType().GetProperties();
List destinationPropertyNames =
destination.GetType().GetProperties().Select(
p => p.Name).ToList();
List propertiesToCopy =
sourceProperties.Where(
p => destinationPropertyNames.Contains(p.Name)).ToList();
foreach (PropertyInfo property in propertiesToCopy)
{
object sourceValue = property.GetValue(source, null);
if (sourceValue != null)
{
PropertyInfo targetProperty =
destination.GetType().GetProperty(property.Name);
targetProperty.SetValue(destination, sourceValue, null);
}
}
}
}
Blogs on the Internet contain many solutions to the same problem with varying degrees of performance and versatility, but I often find these solutions either too complex for simple needs, or not clearly written. Thus, I thought I'd share my solution.
Happy hacking!