How Shallow copy works in Array.Clone() and Array.CopyTo()?

Viewed 32

Possible Duplicate: I have went through similar answers but I am not understanding why a string (reference type) array is acting like deep copy when Array.Clone() or Array.CopyTo() is implemented.

Program 1.

namespace Array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] a = { "1", "2", "3" };
            string [] b = (string[])a.Clone();
            a[1] = "100";

            foreach (var item in b)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(object.ReferenceEquals(a, b));

            if (a == b)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }
        } // void Main
    } // class Program
} // namespace

Output is:

1
2
3
False
No

Program 2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] a = { "1", "2", "3" };
//          string [] b = (string[])a.Clone();
            string[] b = new string[3];
            a.CopyTo(b, 0);
            a[1] = "100";

            foreach (var item in b)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(object.ReferenceEquals(a, b));

            if (a == b)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }
        }
    }
}

Output is:

1
100
3
False
No

I am not understanding how a reference type can be deeply copied? Changes in array A should reflect in b, and a==b should result in true because they are pointing to the same references.

0 Answers
Related