Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c# - Copy Arrays to Array

I have a little Problem with Arrays. I am new in C#.

I try to copy a Int Array into 2 other Int Arrays with

unsortedArray = randomNumbers();

unsortedArray2 = unsortedArray;
unsortedArray3 = unsortedArray;

but, if i sort the unsortedArray2, the unsortedArray3 is sorted too.

Can someone Help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I try to copy a Int Array into 2 other Int Arrays with

The first thing that is important is that in this line :

unsortedArray2 = unsortedArray;

you do not copy the values of the unsortedArray into unsortedArray2. The = is called the assignment operator

The assignment operator (=) stores the value of its right-hand operand in the storage location,

Now the second thing that you need to know to understand this phenomenon is that there are 2 types of objects in C# Reference Types and Value types

The documentation explains it actually quite nicely:

Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.

The solution can be to use the Array.Copy method.

Array.Copy(unsortedArray, 0, unsortedArray2 , 0, unsortedArray.Length);

The CopyTo method would also work in this case

unsortedArray.CopyTo(unsortedArray2 , 0);

Note:this will work because the content of the array is a value type! If it would be also of reference type, changing a sub value of one of the items would lead also to a change in the same item in the destination array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...