I cannot understand the output of the two sets of code snippets given below. How don't really get the concept of shallow copy. How can it be explained?
Class:
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: Isn't string a reference type. Then why p2.Name is printed as "Name1" in snippet 1
Code Snippet 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