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
:
string[] sortedNames = new string[planets.Length]; Array.Copy(planets, sortedNames, planets.Length); 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:
source share