Deep copying

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sweta mistry
    New Member
    • Feb 2012
    • 1

    Deep copying

    Have read on many blogs and sites regarding copyto doing deep copying and clone doing shallow one... when done simple example found both gave same result so what exactly deep copying means? is it truly achievable using copyto?
  • JazibBahir
    New Member
    • Feb 2012
    • 2

    #2
    Deep Copy
    A deep copies all field and make copies of dynamically allocated memory pointed to by the field.A deep copy occurs when an object is copy along with the object to it refer.
    Shallow Copy
    Shallow copy is a bit wise copy an object.A new object is created that has an exact copy of the value in the original object.If any of the field of the object are reference to other object,just the reference address are copied.

    Comment

    • Falkeli
      New Member
      • Feb 2012
      • 19

      #3
      To make it clearer:

      Let's assume we have the following class:
      Code:
      class Example
      {
          private int[] numbers;
          private StringBuilder builder;
      
          public Example()
          {
              numbers = new int[20];
              builder=  new StringBuilder();
          }
      
          // And other methods
      }
      Let example1 be an object of type Example; example2 be a shallow copy of it; and example3 be a deep copy.

      Now, if you do the following code:
      Code:
          example1.numbers[4]=100;
          example2.numbers[4]=50;
          example3.numbers[4]=20;
          Console.Writeln("1: {0}; 2: {1}; 3: {2}", example1.numbers[4], example2.numbers[4], example3.numbers[4]);
      The output will be:
      1: 50; 2: 50; 3: 20

      This is because example1.number s and example2.number s are the same array, since example2 is a shallow copy; example is a different array, since it's a deep copy.

      Comment

      Working...