Click here to Skip to main content
12,825,359 members (36,614 online)
Click here to Skip to main content
Add your own
alternative version


32 bookmarked
Posted 18 Jul 2009

Deep copy of objects in C#

, 18 Jul 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
How to do a deep copy of objects using System.Reflection.


Below you can find a short article on how to do a deep copy of objects using Reflection in C#. Please be aware that this is my first article here (even first article in the English language...)


The class (called HCloner) has a DeepCopy function. It drills down the entire object fields structure (using System.Reflection) and copies it into a new location that is returned after that.

Members that are copied are fields - no need to copy properties since behind every property, there is a field. A property itself cannot hold any value.

Using the code

Let's look at the "core" code:

using System;
using System.Reflection;

namespace HAKGERSoft {

    public class HCloner {

        public static T DeepCopy<T>(T obj) {
                throw new ArgumentNullException("Object cannot be null");
            return (T)Process(obj);

        static object Process(object obj) {
                return null;
            Type type=obj.GetType();
            if(type.IsValueType || type==typeof(string)) {
                return obj;
            else if(type.IsArray) {
                Type elementType=Type.GetType(
                var array=obj as Array;
                Array copied=Array.CreateInstance(elementType,array.Length);
                for(int i=0; i<array.Length; i++) {
                return Convert.ChangeType(copied,obj.GetType());
            else if(type.IsClass) {
                object toret=Activator.CreateInstance(obj.GetType());
                FieldInfo[] fields=type.GetFields(BindingFlags.Public| 
                foreach(FieldInfo field in fields) {
                    object fieldValue=field.GetValue(obj);
                return toret;
                throw new ArgumentException("Unknown type");


Using it is very simple - just call the DeepCopy function.


This is a very alpha-pre version of my function. I'm looking forward for some feedback from you - any issues found will be analysed and fixed (at least, I'll try).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
Poland Poland
No Biography provided

You may also be interested in...

Comments and Discussions

Questionobject[,] Array.Copy Pin
nhatnguyen12345678921-May-16 7:15
membernhatnguyen12345678921-May-16 7:15 
QuestionLooks awesome, bug Throws Exception on System Object Pin
Member 122935161-Feb-16 22:40
memberMember 122935161-Feb-16 22:40 
SuggestionClasses from different assemblies Pin
Defor64-Sep-13 1:26
memberDefor64-Sep-13 1:26 
GeneralMy vote of 1 Pin
memberAYDIN EBRAHIMI HOMAY15-May-13 2:21 
GeneralRe: My vote of 1 Pin
onefootswill28-Jun-14 19:17
memberonefootswill28-Jun-14 19:17 
QuestionError at "return Convert.ChangeType(copied,obj.GetType() ); " Pin
VigneshPT24-Oct-11 11:36
memberVigneshPT24-Oct-11 11:36 
QuestionDoesn't work with inheritance Pin
Sean Wolf16-Sep-11 12:46
memberSean Wolf16-Sep-11 12:46 
GeneralNow it works with structures! [modified] Pin
Brian Coverstone27-Apr-11 16:59
memberBrian Coverstone27-Apr-11 16:59 
GeneralExcellent! Pin
flippydeflippydebop2-Aug-09 0:35
memberflippydeflippydebop2-Aug-09 0:35 
GeneralCircular references. Pin
Andre Luiz Alves Moraes20-Jul-09 4:05
memberAndre Luiz Alves Moraes20-Jul-09 4:05 
GeneralRe: Circular references. Pin
DetoX8322-Jul-09 7:36
memberDetoX8322-Jul-09 7:36 
GeneralHi, think of this..... Pin
tigerharry20-Jul-09 2:20
membertigerharry20-Jul-09 2:20 
GeneralRe: Hi, think of this..... Pin
DetoX8322-Jul-09 7:37
memberDetoX8322-Jul-09 7:37 
GeneralRe: Hi, think of this..... Pin
akshayswaroop18-Nov-09 3:12
memberakshayswaroop18-Nov-09 3:12 
General[My vote of 2] more clarification Pin
Md. Marufuzzaman18-Jul-09 23:44
memberMd. Marufuzzaman18-Jul-09 23:44 
GeneralLooks good Pin
The_Mega_ZZTer18-Jul-09 17:27
memberThe_Mega_ZZTer18-Jul-09 17:27 
Only things I can think of:

1) When copying a class you'll call the default constructor for the class.
1a) You can't create a class that requires arguments to the constructor.
2) Anyone subscribed to events in the old class won't be subscribed to events in the new object. However this may not be desired in some cases anyway.
2a) If the old object was subscribed to any events that weren't initiated by the default constructor the new object won't be subscribed to them.

For #2 I have no idea how to work with event subscriptions in Reflection and for #1 not sure how you could work around that so I'll just say good work for now. Smile | :)

And obviously this won't work with items that access data stored outside the class and expect it to be unique for every class instance, such as Controls which use a native window handle to access the wrapped Windows API control, but that's to be expected.
Generalgj Pin
QuaQua18-Jul-09 16:50
memberQuaQua18-Jul-09 16:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 18 Jul 2009
Article Copyright 2009 by Hakger
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid