0

I am facing a problem in writing generic deep copy method which copies class 1 to class 2 of same structure with different namespace. After searching in net I was able to do at one level of mapping, but problem was if the properties are referring to some other user defined class how to do recursive deep copy. Below is the sample class for better clarity: From the below example I am trying to copy Namespace1.class1 to Namespace2.Class1 (Class1, GenderType, Subject exists both in NameSpace1 and NameSpace2).

Namespace1.Student
{

 String Name {get;set;}
 Int Age {get;set;} 
 List<Subject> lstSubjects {get;set;} //Here we need recursive copy.
 GenderType gender {get;set;}
} 

Enum GenderType
{
  Male,
  Female
}

NameSpace1.Subject
{
   string subjectName {get;set;}
   string lecturereName {get;set;}
}
Abhinay
  • 338
  • 1
  • 7
  • 22

1 Answers1

1

Try using a copy constructor for each of your classes, that can clone all your fields. You might also want to introduce an interface, e.g. called IDeepCloneable, that forces classes to implement a method DeepClone() which calls the copy constructor. To get the cloning type-safe without casting you can use a self-referential structure.

Take a look at the following:

interface IDeepCloneable<out T>
{
    T DeepClone();
}

class SomeClass<T> : IDeepCloneable<T> where T : SomeClass<T>, new()
{        
    // copy constructor
    protected SomeClass(SomeClass<T> source)
    {
        // copy members 
        x = source.x;
        y = source.y;
        ...
   }

    // implement the interface, subclasses overwrite this method to
    // call 'their' copy-constructor > because the parameter T refers
    // to the class itself, this will get you type-safe cloning when
    // calling 'anInstance.DeepClone()'
    public virtual T DeepClone()
    {
        // call copy constructor
        return new T();
    }

    ...
}
mvo
  • 1,138
  • 10
  • 18