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);
}
}
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With