Click here to Skip to main content
15,565,801 members
Articles / Programming Languages / C#
Article
Posted 18 Jul 2009

Stats

147.2K views
1.1K downloads
34 bookmarked

Deep copy of objects in C#

Rate me:
Please Sign up or sign in to vote.
4.83/5 (15 votes)
18 Jul 2009CPOL
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 3:22
jpmik23-Sep-22 3:22 
QuestionYou have rocked in the first article itself. Thank you for your great contribution. Pin
Ashok Login4-Mar-20 20:55
Ashok Login4-Mar-20 20:55 
SuggestionThis change will make parameterless contructors work Pin
Sakkers23-Apr-19 1:27
Sakkers23-Apr-19 1:27 
Questionobject[,] Array.Copy Pin
nhatnguyen12345678921-May-16 7:15
nhatnguyen12345678921-May-16 7:15 
AnswerRe: object[,] Array.Copy Pin
Member 132772109-Jul-17 3:43
Member 132772109-Jul-17 3:43 
QuestionLooks awesome, bug Throws Exception on System Object Pin
Member 122935161-Feb-16 22:40
Member 122935161-Feb-16 22:40 
SuggestionClasses from different assemblies Pin
Defor64-Sep-13 1:26
Defor64-Sep-13 1:26 
GeneralMy vote of 1 Pin
Aydin Homay15-May-13 2:21
Aydin Homay15-May-13 2:21 
GeneralRe: My vote of 1 Pin
onefootswill28-Jun-14 19:17
onefootswill28-Jun-14 19:17 
GeneralRe: My vote of 1 Pin
Octopod25-Jan-18 7:04
Octopod25-Jan-18 7:04 
QuestionError at "return Convert.ChangeType(copied,obj.GetType() ); " Pin
VigneshPT24-Oct-11 11:36
VigneshPT24-Oct-11 11:36 
QuestionDoesn't work with inheritance Pin
Sean Wolf16-Sep-11 12:46
Sean Wolf16-Sep-11 12:46 
GeneralNow it works with structures! [modified] Pin
Brian Coverstone27-Apr-11 16:59
Brian Coverstone27-Apr-11 16:59 
I made a couple mods on it so it will also work with structures and decimals. I also made it an extension method, so you can call it using
obj1 = obj2.DeepCopy()

(I also converted it to VB.net)
<Runtime.CompilerServices.Extension()> Public Function DeepCopy(Of T)(ByVal obj As T) As T
    If obj Is Nothing Then Return Nothing
    Return DirectCast(DeepCopy(obj, New Dictionary(Of Object, Object)()), T)
End Function

Private Function DeepCopy(ByVal obj As Object, ByVal circular As Dictionary(Of Object, Object)) As Object
    If obj Is Nothing Then
        Return Nothing
    End If
    Dim typ As Type = obj.GetType()
    If typ.IsPrimitive OrElse typ Is GetType(String) OrElse typ Is GetType(Decimal) Then
        Return obj
    End If
    If circular.ContainsKey(obj) Then
        Return circular(obj)
    End If
    If typ.IsArray Then
        Dim typeNoArray As String = typ.FullName.Replace("[]", String.Empty)
        Dim elementType As Type = Type.GetType(typeNoArray & ", " & typ.Assembly.FullName)
        Dim arr As Array = obj
        Dim copied As Array = System.Array.CreateInstance(elementType, arr.Length)
        circular(obj) = copied
        For i As Integer = 0 To arr.Length - 1
            Dim element As Object = arr.GetValue(i)
            Dim copy As Object = Nothing
            If element IsNot Nothing AndAlso circular.ContainsKey(element) Then
                copy = circular(element)
            Else
                copy = DeepCopy(element, circular)
            End If
            copied.SetValue(copy, i)
        Next
        Return copied 'Convert.ChangeType(copied, obj.GetType())
    ElseIf typ.IsClass Then 'class
        Dim newobj As Object = Activator.CreateInstance(obj.GetType())
        circular(obj) = newobj
        Dim fields As Reflection.FieldInfo() = typ.GetFields(Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
        For Each field As Reflection.FieldInfo In fields
            Dim fieldValue As Object = field.GetValue(obj)
            If fieldValue Is Nothing Then
                Continue For
            End If
            Dim copy As Object = Nothing
            If circular.ContainsKey(fieldValue) Then
                copy = circular(fieldValue)
            Else
                copy = DeepCopy(fieldValue, circular)
            End If
            field.SetValue(newobj, copy)
        Next
        Return newobj
    ElseIf typ.IsValueType Then 'structure
        Dim newobj As System.ValueType = Activator.CreateInstance(obj.GetType())
        circular(obj) = newobj
        Dim fields As Reflection.FieldInfo() = typ.GetFields(Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
        For Each field As Reflection.FieldInfo In fields
            Dim fieldValue As Object = field.GetValue(obj)
            If fieldValue Is Nothing Then
                Continue For
            End If
            Dim copy As Object = Nothing
            If circular.ContainsKey(fieldValue) Then
                copy = circular(fieldValue)
            Else
                copy = DeepCopy(fieldValue, circular)
            End If
            field.SetValue(newobj, copy)
        Next
        Return newobj
    Else
        Return Nothing
    End If
End Function



-- Modified Tuesday, June 21, 2011 5:07 PM
modified on Tuesday, June 21, 2011 5:12 PM

GeneralExcellent! Pin
flippydeflippydebop2-Aug-09 0:35
flippydeflippydebop2-Aug-09 0:35 
GeneralCircular references. Pin
Andre Luiz Alves Moraes20-Jul-09 4:05
Andre Luiz Alves Moraes20-Jul-09 4:05 
GeneralRe: Circular references. Pin
Hakger22-Jul-09 7:36
Hakger22-Jul-09 7:36 
GeneralRe: Circular references. Pin
Rafi Ben Avi12-Feb-18 21:13
Rafi Ben Avi12-Feb-18 21:13 
GeneralRe: Circular references -> I Found a bug, please add this code Pin
Rafi Ben Avi20-Feb-18 0:22
Rafi Ben Avi20-Feb-18 0:22 
GeneralHi, think of this..... Pin
Binkle@JAM20-Jul-09 2:20
Binkle@JAM20-Jul-09 2:20 
GeneralRe: Hi, think of this..... Pin
Hakger22-Jul-09 7:37
Hakger22-Jul-09 7:37 
GeneralRe: Hi, think of this..... Pin
akshayswaroop18-Nov-09 3:12
akshayswaroop18-Nov-09 3:12 
General[My vote of 2] more clarification Pin
Md. Marufuzzaman18-Jul-09 23:44
professionalMd. Marufuzzaman18-Jul-09 23:44 
GeneralLooks good Pin
The_Mega_ZZTer18-Jul-09 17:27
The_Mega_ZZTer18-Jul-09 17:27 
Generalgj Pin
QuaQua18-Jul-09 16:50
QuaQua18-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.