C# .Net Clone and Copy Objects using Extension Methods

One of my earliest blog articles – Clone Objects in .Net Using Reflections – briefly discusses shallow and deep object copying and cloning.

For more info. on the semantics and what these terms really mean, see referenced wikipedia article.

You may or may not already be familiar with cloning native objects in .Net, such as the datatable. However, for custom classes, you are left to your own creations.

With the advent of extension methods in .Net, the functionality to copy objects can now be moved from static helper classes to inheritable extension methods and has new life and renewed usability. See code snippet below.

Thanks goes to R. Prestol for this one.

public static T GetCopy<T>(this T S)
        T newObj = Activator.CreateInstance<T>();

        foreach (PropertyInfo i in newObj.GetType().GetProperties())

//"EntitySet" is specific to link and this conditional logic is optional/can be ignored
            if (i.CanWrite && i.PropertyType.Name.Contains("EntitySet") == false)
                object value = S.GetType().GetProperty(i.Name).GetValue(S, null);
                i.SetValue(newObj, value, null);           

        return newObj;

MSDN (Extension Methods), http://msdn.microsoft.com/en-us/library/bb383977.aspx
“Clone Objects in .Net Using Reflections”, https://ronniediaz.com/2010/03/02/clone-objects-in-net-using-reflections/
Wikipedia, “Object Copy”, http://en.wikipedia.org/wiki/Object_copy


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 June 21, 2011, in Programming & Development and tagged , , , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: