Click here to Skip to main content
12,297,633 members (23,386 online)
Click here to Skip to main content
Articles » Languages » C# » General » Downloads

Stats

82.1K views
842 downloads
31 bookmarked
Posted

Deep copy of objects in C#

, 18 Jul 2009 CPOL
How to do a deep copy of objects using System.Reflection.
HCloner
HCloner
bin
Debug
HCloner.dll
Properties
HClonerTest
bin
Debug
HCloner.dll
HClonerTest.dll
nunit.framework.dll
HClonerTest.csproj.user
Properties
TestObjects
/**** 
 * 
 * HCloner v0.1 (C) 2009 by HAKGERSoft
 * www.hakger.org
 * 
 */

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");
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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

You may also be interested in...

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