Click here to Skip to main content
16,015,097 members
Articles / Programming Languages / C#

Deep copy of objects in C#

Rate me:
Please Sign up or sign in to vote.
4.83/5 (15 votes)
18 Jul 2009CPOL 156.3K   1.2K   34   24
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:

C#
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)


Written By
Software Developer (Senior)
Poland Poland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
BugShould also deep copy valuetypes Pin
jpmik23-Sep-22 2:22
jpmik23-Sep-22 2:22 
QuestionYou have rocked in the first article itself. Thank you for your great contribution. Pin
Ashok Login4-Mar-20 19:55
Ashok Login4-Mar-20 19:55 
SuggestionThis change will make parameterless contructors work Pin
Sakkers23-Apr-19 0:27
Sakkers23-Apr-19 0:27 
Questionobject[,] Array.Copy Pin
nhatnguyen12345678921-May-16 6:15
nhatnguyen12345678921-May-16 6:15 
AnswerRe: object[,] Array.Copy Pin
Member 132772109-Jul-17 2:43
Member 132772109-Jul-17 2:43 
/// <summary>
        /// 多维数组递归遍历.(标准的递归函数不能用于与迭代器,通过技巧实现了递归迭代器)
        /// </summary>
        public class ArrayLoop
        {
            public Array array;
            int[] indices;
            int currentRank;
            int TheK;
            bool yieldFlag;
            /// <summary>
            /// Initializes a new instance of the <see cref="ArrayLoop"/> class.
            /// </summary>
            /// <param name="a">要遍历的数组</param>
            public ArrayLoop(Array a)
            { array = a; indices = new int[array.Rank]; currentRank = 0; }
            /// <summary>
            /// 多维数组递归遍历.(标准的递归函数不能用于与迭代器,通过技巧实现了递归迭代器)
            /// </summary>
            /// <param name="array">要循环的多维数组.</param>
            /// <param name="currentRank">当前循环递归的维数.</param>
            /// <param name="indices">得到的循环索引</param>
            public IEnumerator GetEnumerator()
            {
                while (Loop(TheK))
                {
                    yieldFlag = false;
                    yield return indices;
                }
            }
            public bool Loop(int start = 0)
            {
                int rank = array.Rank;
                for (int k = start; k < array.GetLength(currentRank); k++)
                {
                    indices[currentRank] = k;
                    if (currentRank == rank - 1)
                    {
                        TheK = k + 1;//保存k;
                        yieldFlag = true;
                        return true;
                    }
                    else
                    {
                        currentRank++;//下一维度循环
                        Loop(0);
                        if (yieldFlag)
                            return true;
                    }
                }
                for (int i = 0; i < rank; i++)
                {
                    if (indices[i] != array.GetLength(i) - 1)//最后一个是indices[i]的每一位都是最大值
                    {
                        currentRank = i; TheK = indices[i] + 1;//为下一轮循环初始化
                        return true;
                    }
                }
                return false;
            }
        }
        private static bool Valid(object sourceObj, object destObj)
        {
            if (sourceObj == null)
                return true;
            Debug.Assert(ReferenceEquals(sourceObj, destObj) == false);
            Type sourceType = sourceObj.GetType();
            Type destType = destObj.GetType();

            if (sourceType != destType)
                return false;
            if (sourceType.IsValueType || sourceType == typeof(string))
                return true;
            if (sourceType.IsArray)
            {
                //Type elementType = Type.GetType(
                //  sourceType.FullName.Replace("[]", string.Empty));
                //针对多维数组字符处理
                int pos1 = sourceType.FullName.IndexOf('[');
                Debug.Assert(pos1 >= 0);
                int pos2 = sourceType.FullName.IndexOf(']', pos1);
                string str1 = sourceType.FullName.Substring(0, pos1);
                string str2 = sourceType.FullName.Substring(pos2 + 1);
                Type elementType = Type.GetType(str1 + str2);


                if (elementType.IsValueType || elementType == typeof(string))
                {
                    return true;
                }
                var sourceArray = sourceObj as Array;
                Array destArray = destObj as Array;

                int rank = sourceArray.Rank;
                ArrayLoop loop = new ArrayLoop(sourceArray);
                foreach (int[] index in loop)
                {
                    if (Valid(sourceArray.GetValue(index), destArray.GetValue(index)) == false)
                        return false;
                }
            }
            if (sourceType.IsClass)
            {
                FieldInfo[] sourcefields = sourceType.GetFields(BindingFlags.Public |
                            BindingFlags.NonPublic | BindingFlags.Instance);
                FieldInfo[] destfields = sourceType.GetFields(BindingFlags.Public |
                            BindingFlags.NonPublic | BindingFlags.Instance);
                for (int i = 0; i < sourcefields.Length; i++)
                {
                    object sourceFieldValue = sourcefields[i].GetValue(sourceObj);
                    object destFieldValue = sourcefields[i].GetValue(destObj);
                    if (Valid(sourceFieldValue, destFieldValue) == false)
                        return false;
                }
                return true;
            }
            else
                return false;//throw new ArgumentException("Unknown type");
        }


        /// <summary>
        /// 通过反射进行深度复制,该版本于2017-6-26调试通过.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">要复制的对象</param>
        /// <returns>返回复制对象的深度副本</returns>
        /// <exception cref="ArgumentNullException">Object cannot be null</exception>
        public static T DeepCopy<T>(T obj)
        {
            if (obj == null)
                throw new ArgumentNullException("Object cannot be null");
            Object dest = Process(obj);
            if (Valid(obj, dest) == false)
                MessageBox.Show("拷贝校验错误!");
            return (T)dest;
            //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)
            {
                //针对多维数组字符处理
                int pos1 = type.FullName.IndexOf('[');
                Debug.Assert(pos1 >= 0);
                int pos2 = type.FullName.IndexOf(']', pos1);
                string str1 = type.FullName.Substring(0, pos1);
                string str2 = type.FullName.Substring(pos2 + 1);
                Type elementType = Type.GetType(str1 + str2);

                //对值类型进行Clone复制,如果C#Array类自带的Clone采用内存拷贝模式,则速度很快
                var array = obj as Array;
                if (elementType.IsValueType || elementType == typeof(string))
                {
                    return array.Clone();
                }

                int rank = array.Rank;
                int[] indices = new int[rank];
                for (int i = 0; i < rank; i++)
                    indices[i] = array.GetLength(i);
                Array copied = Array.CreateInstance(elementType, indices);

                ArrayLoop loop = new ArrayLoop(array);
                foreach (int[] index in loop)
                {
                    copied.SetValue(Process(array.GetValue(index)), index);
                }
                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");
        }

QuestionLooks awesome, bug Throws Exception on System Object Pin
Member 122935161-Feb-16 21:40
Member 122935161-Feb-16 21:40 
SuggestionClasses from different assemblies Pin
Defor64-Sep-13 0:26
Defor64-Sep-13 0:26 
GeneralMy vote of 1 Pin
Aydin Homay15-May-13 1:21
Aydin Homay15-May-13 1:21 
GeneralRe: My vote of 1 Pin
onefootswill28-Jun-14 18:17
onefootswill28-Jun-14 18:17 
GeneralRe: My vote of 1 Pin
Octopod25-Jan-18 6:04
Octopod25-Jan-18 6:04 
QuestionError at "return Convert.ChangeType(copied,obj.GetType() ); " Pin
VigneshPT24-Oct-11 10:36
VigneshPT24-Oct-11 10:36 
QuestionDoesn't work with inheritance Pin
Sean Wolf16-Sep-11 11:46
Sean Wolf16-Sep-11 11:46 
GeneralNow it works with structures! [modified] Pin
Brian Coverstone27-Apr-11 15:59
Brian Coverstone27-Apr-11 15:59 
GeneralExcellent! Pin
flippydeflippydebop1-Aug-09 23:35
flippydeflippydebop1-Aug-09 23:35 
GeneralCircular references. Pin
Andre Luiz Alves Moraes20-Jul-09 3:05
Andre Luiz Alves Moraes20-Jul-09 3:05 
GeneralRe: Circular references. Pin
Hakger22-Jul-09 6:36
Hakger22-Jul-09 6:36 
GeneralRe: Circular references. Pin
Rafi Ben Avi12-Feb-18 20:13
Rafi Ben Avi12-Feb-18 20:13 
GeneralRe: Circular references -> I Found a bug, please add this code Pin
Rafi Ben Avi19-Feb-18 23:22
Rafi Ben Avi19-Feb-18 23:22 
GeneralHi, think of this..... Pin
Binkle@JAM20-Jul-09 1:20
Binkle@JAM20-Jul-09 1:20 
GeneralRe: Hi, think of this..... Pin
Hakger22-Jul-09 6:37
Hakger22-Jul-09 6:37 
GeneralRe: Hi, think of this..... Pin
akshayswaroop18-Nov-09 2:12
akshayswaroop18-Nov-09 2:12 
General[My vote of 2] more clarification Pin
Md. Marufuzzaman18-Jul-09 22:44
professionalMd. Marufuzzaman18-Jul-09 22:44 
GeneralLooks good Pin
The_Mega_ZZTer18-Jul-09 16:27
The_Mega_ZZTer18-Jul-09 16:27 
Generalgj Pin
QuaQua18-Jul-09 15:50
QuaQua18-Jul-09 15: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.