Array.Sort () sorts the source array, not just the copy

This code snippet applies to 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) copy me, although it calls the Sort method only for sorted names.

It doesn't matter which array refers to the second foreach loop, the result 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); } } 
+6
source share
1 answer

Both sortedNames and planets belong to the same array. Basically, both variables point to the same place in memory, so when you call Array.Sort for any variable, changes in the array are reflected by both variables.

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

Contrast this with value types that store data within their own memory allocation, rather than pointing to another place in memory.

If you want to keep planets intact, you can use create a new array and then use Array.Copy to populate the new array with the contents of planets :

 /* Create a new array that 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 can use ToArray and ToArray to create a new ordered array:

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

Some resources that can help with value types and reference types are:

+17
source

Source: https://habr.com/ru/post/978855/


All Articles