C# Class For Making a Deep Copy Clone of an Arbitrary Object

Submitted by Thomas on Sat, 2006-10-14 09:38.

Here is a C# class that can create a deep copy clone of an arbitrary object. The thing that's special about it is that it should work for any class that extends it, so that you don't need to re-write a custom clone() function for every child class (as it seems the C# framework creators would like). This does a deep copy so be careful about members that recursively include one another.

Another way of doing this would be to use serialization . . . I just personally thought the reflection package would be more elegant.

/// 
/// Class for data which can be cloned.
/// 
public class THData
{
    /// 
    /// Function for doing a deep clone of an object.
    /// 
    /// Returns a deep-copy clone of the object.
    public virtual THData DeepClone()
    {
        //First do a shallow copy.
        THData returnData = (THData)this.MemberwiseClone();

        //Get the type.
        Type type = returnData.GetType();

        //Now get all the member variables.
        FieldInfo[] fieldInfoArray = type.GetFields();

        //Deepclone members that extend THData.
        //This will ensure we get everything we need.
        foreach (FieldInfo fieldInfo in fieldInfoArray)
        {
            //This gets the actual object in that field.
            object sourceFieldValue = fieldInfo.GetValue(this);

            //See if this member is THData
            if (sourceFieldValue is THData)
            {
                //If so, cast as a THData.
                THData sourceTHData = (THData)sourceFieldValue;

                //Create a clone of it.
                THData clonedTHData = sourceTHData.DeepClone();

                //Within the cloned containig class.
                fieldInfo.SetValue(returnData, clonedTHData);
            }
        }
        return returnData;
    }
}
( categories: )

Deep Copy Clone of an

Deep Copy Clone of an Arbitrary Object can also be made by some coding through the C++. If there is some code that we can apply from C++, please do share it.

Its very helpful for me and

Its very helpful for me and my friends. I will share this with another to provide them a very useful information. Actually I am also a very good online source PCmarketUSA.com that is the relialble online store to get info about Digital cameras USA, intel computers, western digital hard drives and more.

I tried the code and its

I tried the code and its useful in many ways. All is get it decode so that there would less number of errors and it's easy accessible. Well keep us updating on more such things. Thanks

Really its a

Really its a interesting&helpfull post, I always enjoy reading such posts which provides knowledge based information

I have an object that

I have an object that contains several primitive variables, a custom object, and an ArrayList .

what would be nice is if you

what would be nice is if you could create this as a generic extension method that you could call on any object, rather than having to affect inheritance trees... nice idea though :)

ArrayList

Hello, Thanks very much for your code-- it's exactly what I have been looking for. I have an object that contains several primitive variables, a custom object, and an ArrayList. The custom object is itself being copied along with the clone. The ArrayList, on the other hand, continues to be a reference in my new object (ie. when I clear it from the cloned version, both ArrayLists are emptied) Any advice on this? Thanks

ArrayList

My example code hinges on the deep-cloneable members being subclasses of the THData class. For the case of the ArrayList, you would have to subclass the ArrayList with your own type that handles deep cloning, or have some static method that "knows" (hard-coded) about ArrayLists and can construct a clone of them. You could also try making a subclass of THData with a "has-a" relationship of ArrayList that mimics its container functionality but adds an ArrayList specific DeepClone(). The main advantage to this would be that the THData can use polymorphism to call DeepClone() on your new subclass without having to "know" anything about it. The bad thing is that your subclass class won't work with anything expecting an *actual* ArrayList.

Fieldinfo

It's been a while since I wrote this, but I believe it's a structure for accessing class members anonymously - i.e. it lets you get both the name and the value of the class members when you don't know either. Not exactly speedy but nevertheless a useful thing to have in certain situations.

Sounds good, but what is the

Sounds good, but what is the FieldInfo[]?