C # several methods for copying Arrays

Source: Internet
Author: User

C # several methods for copying Arrays

I was suddenly touched, so I wrote about sharing.

First of all, the array is of the reference type, so be careful not to copy the address while copying, without copying the value!

In fact, when copying arrays, you must use new to open up a new space in the heap for storing arrays. This is effective.

(1)

Int [] pins = {9, 3, 7, 2 };

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

For (int I = 0; I <copy. length; I ++)

{

Copy [I] = pins [I];

}

(2)

Int [] copy = new int [pins. Length];

Pins. CopyTo (copy, 0 );

(3)

Int [] pins = new int [4] {9, 3, 7, 2 };

Int [] alias = pins;

Note that this type of replication is only a reference. It only transmits the data address to the alias array. Therefore, this method is not recommended to copy the array;

(4)

Array. Copy (pins, copy, copy. Length)

(5)

Int [] copy = (int []) pins. Clone ();

The reason why int [] is used for forced type conversion is that the Clone result type is object, so it needs to be forcibly converted to int [].

The Object class is actually the base class of all our classes.

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.