Clone Objects in .Net using Reflections

Clone or Duplicate Objects using .Net Reflections library:

.Net, as well as many other object oriented languages, have strong distinctions between value types and reference types. Objects in .Net, which all inherit the same base object class are reference types. Some reference types, such as with collections or datatables, contain methods which easily allow you to “clone”, “duplicate” or copy the values they contain to another object of the same or differing type.

Classes which you create must define their own methods to achieve this same result, as they cannot inherently be easily “cloned” or “duplicated”. There are two types of cloning, “shallow” or “deep”.

Shallow cloning is standard within System.Object (protected method MemberwiseClone). To implement deep cloning, the interface “IClonable” may be used.

However, an alternate solution exists, using the powerful .Net Reflections which in my opinion is much simpler, and also much easier to modify to your needs. Refer to the code snippet below. Enjoy. 😉

private void CopyObject(ref T DestObj, ref T SourceObj)
foreach (System.Reflection.PropertyInfo PInfo in typeof(T).GetProperties(Reflection.BindingFlags.IgnoreCase | Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance)) {

typeof(T).GetProperty(PInfo.Name, Reflection.BindingFlags.IgnoreCase | Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance).SetValue(DestObj, typeof(T).GetProperty(PInfo.Name, Reflection.BindingFlags.IgnoreCase | Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance).GetValue(SourceObj, null), null);
        /// <summary>
        /// Deep cloning method using reflections which attempts to clone SourceObj into DestObj by value and can even be used across classes with the same property names of different types.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="DestObj"></param>
        /// <param name="SourceObj"></param>
        private static void CopyObject<T1, T2>(ref T1 SourceObj, ref T2 DestObj)
            foreach (System.Reflection.PropertyInfo PInfo in typeof(T1).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance))
                PropertyInfo p1 = typeof(T1).GetProperty(PInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                PropertyInfo p2 = typeof(T2).GetProperty(PInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                if ((p2 != null) && (p2.CanWrite))
                    p2.SetValue(DestObj, p1.GetValue(SourceObj, null), null);

About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on March 2, 2010, in Programming & Development. Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: