Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles. Follow galratner on Twitter Google
Partial object deep copy with extension methods

Deep copy is the process of cloning a complete object into new object of the same type. All of the member values are being copied into new memory addresses and the clone will not be effected by any changed to the original object.
If you need to perform a partial deep clone, a cloning method that simply copied values of fields from one object into another object of the same type, without creating a new perfect clone, you might find this extension method useful.

public static class ObjectExtensions

    {

        /// <summary>

        /// Copy all of the public properties between the objects

        /// </summary>

        /// <typeparam name="T">The type of the object</typeparam>

        /// <param name="copyFrom">The source</param>

        /// <param name="copyTo">The destination</param>

        /// <param name="copyParentProperties">Copy any properties from parent types</param>

        public static void CopyTo<T>(this T copyFrom, T copyTo, bool copyParentProperties)

        {

            PropertyInfo[] props;

            if(copyParentProperties)

                props = typeof(T).GetProperties();

            else

                props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

 

            for (int i = 0; i < props.Length; i++){

                var propertyValue = copyFrom.GetType().GetProperty(props[i].Name).GetValue(copyFrom, null);

                copyTo.GetType().GetProperty(props[i].Name).SetValue(copyTo, propertyValue, null);

            }

        }


Usage looks like this:

mySource.CopyTo<myType>(myDestination, false);

Enjoy.


Posted 6 May 2010 6:40 AM by Gal Ratner
Filed under:

Comments

DotNetKicks.com wrote Partial object deep copy with extension methods
on 6 May 2010 10:01 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Powered by Community Server (Non-Commercial Edition), by Telligent Systems