Click here to Skip to main content
Click here to Skip to main content

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.

Introduction

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...)

Background

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) {
            if(obj==null)
                throw new ArgumentNullException("Object cannot be null");
            return (T)Process(obj);
        }

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

    }
}

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

History

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).

License

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

Share

About the Author

Hakger
Software Developer (Senior)
Poland Poland
No Biography provided

Comments and Discussions

 
SuggestionClasses from different assemblies PinmemberDefor64-Sep-13 0:26 
GeneralMy vote of 1 PinmemberAYDIN EBRAHIMI HOMAY15-May-13 1:21 
GeneralRe: My vote of 1 Pinmemberonefootswill28-Jun-14 18:17 
QuestionError at "return Convert.ChangeType(copied,obj.GetType() ); " PinmemberVigneshPT24-Oct-11 10:36 
QuestionDoesn't work with inheritance PinmemberSean Wolf16-Sep-11 11:46 
GeneralNow it works with structures! [modified] PinmemberBrian Coverstone27-Apr-11 15:59 
GeneralExcellent! Pinmemberflippydeflippydebop1-Aug-09 23:35 
GeneralCircular references. PinmemberAndre Luiz Alves Moraes20-Jul-09 3:05 
Hi,
 
I Already done some code like yours and one of the important things to handle is Circular References.
 
For example if you have a tree class like this:
 
public class Tree
{
  public TreeNode _root;
}
 
public class TreeNode
{
  public TreeNode _parent;
  public TreeNode _lChild;
  public TreeNode _rChild;
 

  public TreeNode(TreeNode parent)
  {
    _parent = parent;
  }
}
 
When you call the method to a object of Tree your code will start do copy the nodes of the tree.
 
The big problem is that de root node of a tree is the parent of some child, so, when you start to copy the child of the root, your code will look into _parent field and will try to copy the root node again. And this cycle will continue until a stack overflow.
 
To solve that problem i used a collection of cloned objects. It was something like this;
 
public class CloneList
{
  private IList _originals;
  private IList _clones;
 
  public CloneList()
  {
    _originals = new ArrayList();
    _clones = new ArrayList();
  }
  
  public object getCloneForOriginal(object original)
  {
    if (_originals.Contains(original))
    {
        return _clones[_originals.IndexOf(original)];
    }
    else
    {
      return null;
    }
  }
}
Thumbs Up | :thumbsup:
GeneralRe: Circular references. PinmemberDetoX8322-Jul-09 6:36 
GeneralHi, think of this..... Pinmembertigerharry20-Jul-09 1:20 
GeneralRe: Hi, think of this..... PinmemberDetoX8322-Jul-09 6:37 
GeneralRe: Hi, think of this..... Pinmemberakshayswaroop18-Nov-09 2:12 
General[My vote of 2] more clarification PinmemberMd. Marufuzzaman18-Jul-09 22:44 
GeneralLooks good PinmemberThe_Mega_ZZTer18-Jul-09 16:27 
Generalgj PinmemberQuaQua18-Jul-09 15:50 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 18 Jul 2009
Article Copyright 2009 by Hakger
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid