Array assignment methods in C #

Source: Internet
Author: User
There are several ways to copy array in C #

Replication between arrays, int[] pins = {9,3,4,9};int [] alias = pins; There is an error and the source of the error, the above code is not a mistake, but it is not a copy at all, because pins and alias are references, exist on the stack, and data 9, 3,4,3 is an int object that exists in the heap, int [] alias = pins; just create another reference, alias and pins point to {9,3,4,3} at the same time, and when one of the references is modified, it is bound to affect the other. Copying means creating a new object that is identical to the object being copied, which should be replicated in the C # language in the following 4 ways.

Method One: Use a 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 Two: 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 Three: Use a static method of the array class copy ()

int []pins = {9,3,7,2}

int []copy3 = new Int[pins.length];

Array.copy (pins,copy3,copy. Length);

Method four: Using one of the instance methods in the array class, Clone (), can be called one time, the most convenient, but the Clone () method returns an object, so cast to the appropriate class type.

int []pins = {9,3,7,2}

int []COPY4 = (int []) pins. Clone ();

Method Five:

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[] Copyafter = (string[]) student. ToArray (typeof (String));

Two arrays merge, and finally assign the merged result to the Copyafter array, this example can be flexible, many places can use


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.