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

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#?

Tags:

C#

Arrays

Sorting