Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)? Also i would like to know how to know the objId of an object in C# just how we get in cpp like obj.getObjId().Tried getHashCode() and does not seem to help as they are the same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading