Tim
Tim

Reputation: 15

Sorting an array effecting previous arrays

I'm trying to sort an array to find the mean of it. After finding the median I'm looking to continue using the array. When using the code,

            double[] views, viewssorted;
            views = new double[] {9.0, 1111.0,  2.0 };
            viewssorted = views;
            Array.Sort(viewssorted);

both my viewssorted and views arrays get sorted. How do I make it so that only viewssorted gets sorted?

Upvotes: 0

Views: 50

Answers (3)

CurtDotNet
CurtDotNet

Reputation: 11

Arrays are reference types in C#, that's why they both sort.

You can do

views.CopyTo(viewssorted)

Or

viewssorted = views.Clone()

Upvotes: 0

Max Play
Max Play

Reputation: 4038

Your problem is that arrays are essentially classes and as such reference types. A reference type does not hold a value but rather points to an area in your memory.

When you write viewssorted = views; you are assigning the same reference you have in views to viewssorted. They are essentially the same object referenced by two variables.

To create a copy of the array, but with the same internal references (in your case the same double values), use Array.Clone().

This would be

viewssorted = (double[])Array.Clone(views);

Upvotes: 1

napuzba
napuzba

Reputation: 6288

When using

viewssorted = views;

viewssorted and views are references to the same array. Thus, any change in the first will be reflected in the second.

You should use Array.Clone to make a copy of the array.

viewssorted = (double[]) views.Clone();;

Upvotes: 0

Related Questions