Click here to Skip to main content
15,879,326 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 153.6K   1.2K   34  
How to do a deep copy of objects using System.Reflection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HAKGERSoft;
using NUnit.Framework;
using System.Reflection;
using System.ComponentModel;

namespace HAKGERSoft {

    public class Differ {

        public static void Check(object a,object b){
            if(a==null && b==null)
                return;
            Type t1=a.GetType();
            Type t2=b.GetType();
            if(t1!=t2) {
                Throw("Types are not same, type(1)={0}, types(2)={1}",t1.ToString(),t2.ToString());
            }
            else if(t1.IsValueType) {
                if(!a.Equals(b)) {
                    Throw("Value type not same!");
                    return;
                }
            }
            else if(a is string) {
                if((string)a != (string)b)
                    Throw("Value diff");
            }
            else if(t1.IsClass) {
                if(object.ReferenceEquals(a,b))
                    Throw("Reference equals");
                FieldInfo[] fields=t1.GetFields(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
                foreach(FieldInfo field in fields) {
                    object o1=field.GetValue(a);
                    object o2=field.GetValue(b);
                    Check(o1,o2);
                }
            }
        }

        static void Throw(string format,params object[] args){
            Throw(string.Format(format,args));
        }

        static void Throw(string message){
            throw new ArgumentException(message);
        }


    }
}

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)


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