CKTIS / C#
Array.Clone and Array.Sort: sorting an array copy
Combine Array.Clone with Array.Sort to obtain a sorted array copy without changing the original element order. Learn how a shallow copy differs from sharing the same array.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
int[] sorted = (int[])original.Clone();
Array.Sort(sorted);Array.Clone creates a new array with the same runtime type, but returns object, so the example needs a cast to int[]. The assignment int[] sorted = original; does not create a copy: both variables would refer to the same array.
The copy is shallow: element values are copied, not entire object graphs. For int[], this produces independent numeric elements. If elements are references, both arrays still refer to the same objects; changing such an object's state can be visible through both arrays.
Array.Sort(sorted) rearranges the supplied array in place and returns void, not a new array. For int[], the default order is ascending. Overloads let you supply a custom comparer or sort a selected range. Sorting is unstable: elements that compare equal need not retain their relative order.
Clone first and then sort the copy when the original order must remain unchanged. In the example, original keeps 4, 1, 3, 1, while sorted contains 1, 1, 3, 4. Both APIs are available in .NET 10; this example does not require preview language features.
Examples
using System;
internal static class Program
{
private static void Main()
{
int[] original = { 4, 1, 3, 1 };
int[] sorted = (int[])original.Clone();
Array.Sort(sorted);
Console.WriteLine("original: " + string.Join(", ", original));
Console.WriteLine("sorted: " + string.Join(", ", sorted));
}
}Result
original: 4, 1, 3, 1 sorted: 1, 1, 3, 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.