Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.Sort() sorts original array and not just copy

Tags:

arrays

c#

sorting

This code snippet is from C# 2010 for Dummies. What confuses me is that when using the Array.Sort() method, both my copy of the array (sortedNames) and the original array (planets) get sorted, even though it only calls the Sort method on sortedNames.

It doesn't matter which array the second foreach loop references, the output is the same.

static void Main(string[] args)
{
    Console.WriteLine("The 5 planets closest to the sun, in order: ");
    string[] planets = new string[] { "Mercury","Venus", "Earth", "Mars", "Jupiter"};
    foreach (string planet in planets)
    {
        Console.WriteLine("\t" + planet);
    }
    Console.WriteLine("\nNow listed alphabetically: ");


    string[] sortedNames = planets;
    Array.Sort(sortedNames);

    foreach (string planet in planets)
    {
        Console.WriteLine("\t" + planet);
    }
}
like image 973
Bill Nazzaro Avatar asked Nov 29 '14 01:11

Bill Nazzaro


People also ask

How do you sort an array without changing the original array?

To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.

Does sort change original list?

The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection. The older list. sort() method is an alternative detailed below.

What does Arrays sort () do?

The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

Both sortedNames and planets refer to the same array. Basically both variables point to the same location in memory, so when you call Array.Sort on either variable, the changes to the array are reflected by both variables.

Since arrays in C# are reference types, both sortedNames and planets "point" to the same location in memory.

Contrast this with value types, which hold data within their own memory allocation, instead of pointing to another location in memory.

If you wanted to keep planets intact, you could use create a brand new array, then use Array.Copy to fill the new array with the contents of planets:

/* Create a new array that's the same length as the one "planets" points to */
string[] sortedNames = new string[planets.Length];

/* Copy the elements of `planets` into `sortedNames` */
Array.Copy(planets, sortedNames, planets.Length);

/* Sort the new array instead of `planets` */
Array.Sort(sortedNames);

Or, using LINQ you could use OrderBy and ToArray to create a new, ordered array:

string[] sortedNames = planets.OrderBy(planet => planet).ToArray();

Some resources that might help with value types and reference types:

  • Value types and Reference Types (MSDN)
  • What is the difference between a reference type and value type in c#?
like image 140
Andrew Whitaker Avatar answered Oct 21 '22 10:10

Andrew Whitaker