Shallow Copy Object Properties between different types

Have you ever repeatedly written assignment code, which just copies same named properties from object of one type to object of another? Here is a simple extension method that can be used to shallow copy a non-collection type object. This copies the values from a source type to a destination type, by matching property names.

public static void CopyTo(this Object source,
                          Object destination,
                          string excludeProperties)
{
      Type SourceType = source.GetType();
      Type DestinationType = destination.GetType();
      string[] excluded = null;

      if (!String.IsNullOrEmpty(excludeProperties))
      {
          excluded = excludeProperties.Split(',');
      }

      PropertyInfo[] properties = DestinationType.GetProperties();

      foreach (var destProperty in properties)
      {
          if ((!destProperty.CanWrite)
              || (excluded != null && excluded.Contains(destProperty.Name)))
               continue;

          var sourceProperty = SourceType.GetProperty(destProperty.Name);

          if(sourceProperty == null || !sourceProperty.CanRead)
              continue;

          destProperty.SetValue(destination,
                                sourceProperty.GetValue(source, null), null);
       }
}

Of course this could be made better by using Expression Trees – that would be more efficient than reflection, especially if this is done in a tight loop. But for one-time operations, this is good enough.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax