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)?