Extending CopyHelper using Extension Methods

2008, Jul 22    

In my last two posts, I have been developing a small utility library to do the grunt work of copying data from an instance of one class to an instance of another type. The Copier class from my last post allows me to copy all public properties from one class to another class as long as the properties have the same name and type. All that is done with one line of code;

Copier.Copy( customer ).To( view );</code></pre>
</div>

Today, I am going to use extension methods to simplify the above code even further. I want to be able to write

customer.CopyTo( view );</code></pre>
</div>

or if we want to rely on type inferencing with the generic CopyTo method, you could write it as simply as

customer.CopyTo( view );</code>

How is this done? Using extension methods, it was actually much simpler than yesterday's Copier class. In fact, it just ended up being one line of code for the CopyTo method and for the CopyFrom method. I simply wrapped the CopyHelper class like this.

public static class CopierExtensions
{
    public static void CopyTo( this object from, T to ) where T : class
    {
        CopyHelper.Copy( from.GetType(), from, typeof( T ), to );
    }

    public static void CopyFrom( this object to, T from ) where T : class
    {
        CopyHelper.Copy( typeof( T ), from, to.GetType(), to );
    }
}</code></pre>
</div>

The only problem I have with this is that the class that the extension methods are applied to are not constrained by an interface, so all matching properties are copied. Does anyone have any ideas on that?

I have uploaded a copy of the solution for this project along with an NUnit test project. Take a look, use it if you like and feel free to give me suggestions for improvements.

In the next few posts I was thinking of extending these classes even further. I might add attributes that allow you to ignore certain properties, maybe add an attribute that specifies interfaces that you are allowed to copy to, possibly an attribute that allows properties to automatically be converted between types. What would you find useful or like to see? Would you like to see a post on the performance using these methods?