0

Deep and shallow constructor work like below.

using System;


namespace StringArrayInitializationTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lsa = { "one", "two", "three" };

            // Shallow copy
            MyClass myObj = new MyClass(lsa);
            myObj.EditFirst();
            Console.WriteLine("First array item in local : " + lsa[0]);
            myObj.CheckFirst();
            // Deep copy
            MyCopyClass mycpyObj = new MyCopyClass(lsa);
            mycpyObj.EditFirst();
            Console.WriteLine("First array item in local : " + lsa[0]);
            mycpyObj.CheckFirst();
        }
    }

    class MyClass
    {
        private string[] sa = null;
        public MyClass(string[] psa)
        {
            sa = psa;
        }
        public void CheckFirst()
        {
            Console.WriteLine("First array item in object : " + sa[0]);
        }
        public void EditFirst()
        {
            sa[0] = "zero";
        }
    }
    class MyCopyClass
    {
        private string[] sa = null;
        public MyCopyClass(string[] psa)
        {
            sa = new string[psa.Length];
            for(int i=0; i<psa.Length; i++)
            {
                sa[i] = psa[i];
            }
        }
        public void CheckFirst()
        {
            Console.WriteLine("First array item in object : " + sa[0]);
        }
        public void EditFirst()
        {
            sa[0] = "one";
        }
    }
}

But the question here is can I get deep constructor with shortcut. Some thing look like below which is not syntactically correct.

        public MyClass(string[] psa)
        {
            sa = new string[](psa); // Syntax error here
        }

What is the second way to initialize string array in deep copy behavior (with small code like above)?

1 Answer 1

3
sa = psa.ToArray();

would do the job. This takes the sequence of values and copies it into another array.


Please note this goes for value-types and (immutable) strings. If you want deep-copies of reference types, you have to find a way to deep copy the reference type first:

// assuming a custom "DeepCopyMethod" exists for your type:
sa = psa.Select(DeepCopyMethod).ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

with using System.Linq;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.