Home > Article > Backend Development > Array assignment method in c#
There are many ways to copy arrays in C#
Copy between arrays, int[] pins = {9,3,4,9};int [] alias = pins; There is an error here, and it is also the source of the error. The above code There is no error, but it is not a copy at all, because pins and alias are references and exist on the stack, and the data 9,3,4,3 is an int object existing on the heap, int [] alias = pins; is nothing but Create another reference, alias and pins point to {9, 3, 4, 3} at the same time. When one of the references is modified, it will inevitably affect the other. Copying means to create a new object that is the same as the copied object. There should be the following four methods to copy in C# language.
Method 1: Use for loop
int []pins = {9,3,7,2}
int []copy = new int[pins.length];
for(int i =0; i!=copy.length;i++)
{
copy[i] = pins[i];
}
Method 2: Use the CopyTo() method in the array object
int [] pins = {9,3,7,2}
int []copy2 = new int[pins.length];
pins.CopyTo(copy2,0);
Method 3: Use a static member of the Array class Method Copy()
int []pins = {9,3,7,2}
int []copy3 = new int[pins.length];
Array.Copy(pins,copy3,copy.Length );
Method 4: Use an instance method Clone() in the Array class. It can be called once and is the most convenient. However, the Clone() method returns an object, so it must be cast to the appropriate class type.
int []pins = {9,3,7,2}
int []copy4 = (int [])pins.Clone();
Method 5:
string[] student1 = { "$", "$", "c", "m", "d", "1", "2", "3", "1", "2", "3" };
string[] student2 = { "0", "1", "2", "3", "4", "5", "6", "6", "1", "8", "16", "10","45", "37", "82" };
ArrayList student = new ArrayList();
foreach (string s1 in student1)
{
student.Add(s1); }
foreach (string s2 in student2)
{
student.Add(s2);
}
string[]After copy = (string[])student.ToArray(typeof(string));
Merge two arrays, and finally assign the merged result to the copyAfter array. This example can be flexible and can be used in many places
For more articles related to array assignment methods in c#, please pay attention to the PHP Chinese website!