difference between CopyTo () and Clone () in the C # array (turn)

Source: Internet
Author: User
Tags shallow copy

There are many beginners who are confused about the difference between CopyTo () and Clone (). Searching the web, most programmers explain the problem to the difference between a shallow copy and a deep copy, and the light copy and deep copy are clearly explained, but this does not make the beginner less puzzled. So I hereby write something. , explain the similarities and differences between the two methods, while interpreting the lower and deep copies.

I believe most C # programmers have a good habit of looking up MSDN, but the most important difference in MSDN is that one method creates a new array object, and one method simply duplicates the array reference. There is no mistake in that sentence, And that's what distinguishes them. It's just that it's confusing. What is the difference? Here's what they have in common: CopyTo () and Clone () are both shallow copies. For shallow copies: If the members in the array are value types such as int, Float,double,byte, etc.), the value is completely copied into the target array, if it is a reference type (such as a user-defined type: Class Student,class people, or a class type in a class library: ArrayList, etc.), Refers to the copy reference to the destination array. Sometimes the text is not as easy to understand as the code. But here it may be easier to understand with diagrams, look at the following figure:

Suppose you create a student class array student[], and then shallow copy to another student class array student1[].

It is easy to see from the diagram that a shallow copy is simply a copy reference for a reference type. Modifying the value in memory through an array affects the reference of another array to the memory object.

So what's the difference between the CopyTo () and the Clone () method? In fact, the difference between them is that the biggest difference on MSDN is the difference in usage. We can look at the return value of the VS pop-up smart prompt, and the return value for CopyTo () is void, The use method is Array1.copyto (array2,0), where Array2 must be an already instantiated array. The return value of Clone () is object. Use the following method Array2 = Array1.clone (); Where Array2 does not have to be instantiated. In this way, I believe it is easy to understand the difference between the two methods. There is no difference in nature. If you copy all the arrays, you use Clone (). But if it's just a copy of a part, you can choose CopyTo (), CopyTo () The parameter hint is such as CopyTo (Array Array,int Index). The second argument index (index) indicates that copying begins with the first few objects in the array.

Believe it. It should be easy to understand CopyTo () and Clone (). The difference between a shallow copy and a deep copy is explained below.

As mentioned above, a shallow copy duplicates a value for a value type, and a reference to a reference type (similar to a pointer). Deep copy is a complete creation of new objects. Creates a new object for all objects in the original array. Changes to the new array do not affect the values or objects in the original array. But how to achieve deep copy? NET Library there appears to be no deep copy method. This is related to the principle of implementing deep copy. If the user wants to implement a deep copy. Expect two identical but unrelated arrays. You must write your own method, copy each object in the original array, and deep into the object in the object ... The object in is a value type, because only the value type is a full copy, modifying one value does not affect the same value. That's a little hard to understand. The method for implementing deep copy, as shown in the following illustration:

In the figure, the blue represents the value type, direct copy, and red represents the reference type, which requires depth until the last layer is copied to the value type (the picture is less elegant, but basically expresses the principle of deep copy).


1 are all light copies.

2 Copies all source to destination.

The destination of the 3 CopyTo is instantiated, and the destination of the clone must be instantiated.

Using System;
public class Samplesarray

public static void Main ()

Creates and initializes two new Arrays.
Array Mysourcearray = Array.CreateInstance (typeof (String), 6);
Mysourcearray.setvalue ("three", 0);
Mysourcearray.setvalue ("napping", 1);
Mysourcearray.setvalue ("Cats", 2);
Mysourcearray.setvalue ("in", 3);
Mysourcearray.setvalue ("The", 4);
Mysourcearray.setvalue ("Barn", 5);
Array Mytargetarray;
Array Mytargetarray = Array.CreateInstance (typeof (String), 15);
Mytargetarray.setvalue ("The", 0);
Mytargetarray.setvalue ("Quick", 1);
Mytargetarray.setvalue ("Brown", 2);
Mytargetarray.setvalue ("Fox", 3);
Mytargetarray.setvalue ("Jumps", 4);
Mytargetarray.setvalue ("Over", 5);
Mytargetarray.setvalue ("the", 6);
Mytargetarray.setvalue ("lazy", 7);
Mytargetarray.setvalue ("Dog", 8);

Displays the values of the Array.
Console.WriteLine ("The target Array contains the following (before and after copying):");
Printvalues (Mytargetarray, "");

Copies the source array to the target array, starting at index 6.
Mysourcearray.copyto (Mytargetarray, 6); This is not compiled, because CopyTo requires destination to be instantiated
Mytargetarray = (string[]) mysourcearray.clone (); No problem, because clone does not require destination to be instantiated

Displays the values of the Array.
Printvalues (Mytargetarray, "");

Console.ReadLine ();

public static void Printvalues (Array myarr, char myseparator)
System.Collections.IEnumerator myenumerator = Myarr.getenumerator ();
int i = 0;
int cols = Myarr.getlength (myarr.rank-1);
while (Myenumerator.movenext ())
if (I < cols)
Console.WriteLine ();
i = 1;
Console.Write ("{0}{1}", Myseparator, myenumerator.current);
Console.WriteLine ();

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.