0

I know that CopyTo requires to have a destination array while Clone returns a new array. but i have read that both perform shallow copy and refer same instance..

So if I have

A = [1,2,3,4] 

and I Clone it and get

B = [1,2,3,4]. 

Now, if I change

B[0] = 9. 

This means that A will now be

A = [9,2,3,4]. 

Is that correct? And is this correct for CopytTo()?

2
  • 5
    why don't you try it? it will take less time to try than to wait for an answer. Commented Mar 18, 2014 at 4:51
  • Did you try it? If you have Visual Studio handy, you could write a short code snippet and get your answer in a couple of minutes. Commented Mar 18, 2014 at 4:51

3 Answers 3

1

When you do B[0] = 9 you are replacing element with 0 index in B array, so A array will stay the same (you don't change it actually) and it doesn't matter which method (CopyTo or Clone) you are using (since A doesn't reference to B).

Sign up to request clarification or add additional context in comments.

2 Comments

so if I change A array than accordingly B will be changed or not?
If you Clone or CopyTo, then B will not be changed since they are referencing two different memory addresses.
1

No. Clone typically creates a new instance and copy whatever in the original object to it. Other words, A and B are pointing at two different memories. In your case, A will remain the intact.

A = [1, 2, 3, 4] 

A will only be changed if we set

B = A; 

In this case, both A and B are pointing at the same address.

However, if we set

B = A.Clone(); 

Then whatever changes made to B will not affect A. CopyTo also does the same process as Clone except that it lets you specify the position in A to start copying data to B.

Comments

0

The MSDN documentation of Array.Clone specifically goes through this example to show that no it will not change both copies.

This makes sense, as the array object will be a series of memory addresses pointing to the object. When you clone the array, you create a copy of the memory addresses. If you change one of the arrays, you change the value of the memory address. Hence the change will be comfined to that array.

http://msdn.microsoft.com/en-us/library/system.array.clone(v=vs.110).aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.