Shallow copy - Link type abnormal

I cannot understand the output of the two sets of code snippets below. How not to get a shallow copy concept. How can this be explained?

Grade:

 public class Person : ICloneable
 {
    public string Name;        
    public int[] arr; 
    public object Clone()
    {
        return this.MemberwiseClone();
    }
 }

Code Snippet 1:

 static void Main(string[] args)
    {
        Person p1 = new Person();
        p1.Name = "Name1";
        p1.arr = new int[5] {1,2,3,4,5 };
        Person p2 = (Person)p1.Clone();

        p1.Name = "Name2";
        p1.arr[0] = 11;

        Console.WriteLine(p2.Name);
        Console.WriteLine(p2.arr[0].ToString());
        Console.Read();

    }

Output: Name1 11

Doubt: not a reference type. Then why p2.Name is printed as "Name1" in fragment 1

Fragment Code 2:

static void Main(string[] args)
    {
        Person p1 = new Person();
        p1.Name = "Name1";
        p1.arr = new int[5] { 1, 2, 3, 4, 5 };
        Person p2 = (Person)p1.Clone();

        p1.Name = "Name2";
        p1.arr = new int[5] { 11, 12, 13, 14, 15 };

        Console.WriteLine(p2.Name);
        Console.WriteLine(p2.arr[0].ToString());
        Console.Read();

    }

Output: Name1 1

+3
source share
4 answers

The array int [] in your example is a reference type. This means that both p1.arrand p2.arrpoint to the same array in memory.

If you change the value of the first index p1.arr, it means that the value of the first index also changes p2.arr. Consequently, the behavior in code snippet 1.

, p1. p1.arr . p2.arr "" . , p2.arr[0] 1.

, , , , :

p1.Name = "Name2";

:

p1.Name = new String("Name2");

, int []. p1.Name, p1.Name . p2.Name - "" , "Name1". p1.Name, .

+4

.

. , , , , , .

p1.Name = "Name2"; // new String -equivalent to p1.Name = new string("Name2")
p1.arr[0] = 11; //updated array element

, , . String ( ) p1.Name, , . p2.Name( ) , "Name1"

- p1.Name p2.Name. , string.replace, .

, .

+2

Pls :

static void Main(string[] args)
{
    Person p1 = new Person();
    p1.Name = "Name1";
    p1.arr = new int[5] {1,2,3,4,5 };
    Person p2 = (Person)p1.Clone();

    p1.Name = "Name2"; //Now p1.Name points to a new memory location
    //But p2.Name is still pointing to the location p1.Name had
    // originally pointed to.

    p1.arr[0] = 11; //here p1.arr and p2.arr are pointing to the same place
    //So since you are changing the value of one location it gets 
    //reflected in both

    Console.WriteLine(p2.Name); //Prints Name1
    Console.WriteLine(p2.arr[0].ToString()); //Prints 11
    Console.Read();

}

,

p1.arr = new int[5] { 11, 12, 13, 14, 15 };

p1.arr is done to indicate a completely new location. (for example, what happens when you do p1.Name = "Name2"). So this does not affect p2.arr, which still points to the same place that p1.arr used to point to. (ie to the array {1,2,3,4,5})

0
source

Source: https://habr.com/ru/post/1706110/


All Articles