Search code examples
c#deep-copy

Deep copy in c# using a method


I have classes :

public class ComplexObject
{
 public int number = 12;
 public anotherComplexObject aco;
}

public class Experiment
{
  public ComplexObject GetDeepCopyObj(ComplexObject obj)
  {
     var copiedData = new ComplexObject 
     {
            number = obj.number,
            aco = obj.aco
     };
      
     return copiedData ;
  }
  
  static void Main()
  {
   ComplexObject c1 = new ComplexObject();
   c1.number = 3;
   c1.aco = new anotherComplexObject{...};

   Experiment experiment = new Experiment();
   ComplexObject c2 = experiment.GetDeepCopyObj(c1); //line 99
  }
}

Here, when i make a call to GetDeepCopyObj(c1) in "line 99", will c2 be a deep copied object of c1 in c#(aco field is reference type..Still it will have same reference right? i am assuming a deep copy will not happen here)?


Solution

  • aco field is reference type..Still it will have same reference right? i am assuming a deep copy will not happen here)

    Yes, that's what reference-types are about and therefor your aco-property of both c1 and c2 will reference the exact same object.

    A deep copy, as the term implies, will create a completely new instance down the entire oject-graph. So when your ComplexObject has some anotherConplexObject in it, you should deep-copy that as well until the most atomic data-structures, which eventually will be value-types and strings.

    As per ypur second question: I don't know of any global function getObjId for any object, that returns the objects id, as not all classes share the concept of an id at all. What you presumably mean is the pointers adress, which is where the object is stored physically. This concept has nothing to do with an id, though.