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

Deep copy of objects in C#

By , 18 Jul 2009
 

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)

About the Author

Hakger
Software Developer (Senior)
Poland Poland
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberAYDIN EBRAHIMI HOMAY15-May-13 1:21 
QuestionError at "return Convert.ChangeType(copied,obj.GetType() ); "memberVigneshPT24-Oct-11 10:36 
QuestionDoesn't work with inheritancememberSean Wolf16-Sep-11 11:46 
GeneralNow it works with structures! [modified]memberBrian Coverstone27-Apr-11 15:59 
GeneralExcellent!memberflippydeflippydebop1-Aug-09 23:35 
GeneralCircular references.memberAndre Luiz Alves Moraes20-Jul-09 3:05 
GeneralRe: Circular references.memberDetoX8322-Jul-09 6:36 
GeneralHi, think of this.....membertigerharry20-Jul-09 1:20 
GeneralRe: Hi, think of this.....memberDetoX8322-Jul-09 6:37 
GeneralRe: Hi, think of this.....memberakshayswaroop18-Nov-09 2:12 
General[My vote of 2] more clarificationmemberMd. Marufuzzaman18-Jul-09 22:44 
GeneralLooks goodmemberThe_Mega_ZZTer18-Jul-09 16:27 
GeneralgjmemberQuaQua18-Jul-09 15:50 

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

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