Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Shallow array cloning and sorting with Comparison<T>

Use `Array.Clone()` to create a separate array, then sort it in place with `Array.Sort` and a `Comparison<T>` delegate. The clone can still share element objects with the original.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

using System;

int[] original = [3, 1, 2];
int[] copy = (int[])original.Clone();
Comparison<int> comparison = (x, y) => x.CompareTo(y);
Array.Sort<int>(copy, comparison);

// API signatures (namespace System):
// Array: public virtual object Clone();
// Array: public static void Sort<T>(T[] array, Comparison<T> comparison);
// public delegate int Comparison<in T>(T x, T y);

System.Array.Clone/Sort and Comparison<T> covers two operations: cloning an array and sorting it with a delegate. In C# 12 and .NET 8, the instance method System.Array.Clone() creates a separate array of the same runtime type. Its return type is object, so for a T[] use (T[])original.Clone(). Assignment with copy = original creates no array: both variables refer to the same instance.

The clone is shallow: value-type elements are copied by value, and reference-type elements are copied as references, not as new objects. Reordering or replacing an entry in the clone leaves the original array's slots unchanged, but changing a shared object's state is visible through both arrays.

The static overload Array.Sort<T>(T[], Comparison<T>) sorts the whole one-dimensional, zero-based array in place and returns void. It uses a System.Comparison<T> delegate rather than an IComparer<T> object or the default order. Given x and y, a negative result puts x before y, zero means they sort as equivalent, and a positive result puts x after y. For int keys, use CompareTo instead of subtraction, which can overflow.

Provide a consistent, transitive ordering and return zero for an element compared with itself. Sorting is unstable: elements that compare equal may change relative order. Passing null for the array or delegate throws ArgumentNullException. If sorting fails, do not assume the array was left unchanged.

Examples

using System;
using System.Linq;

Item[] original = [new Item("B", 20), new Item("A", 10), new Item("C", 30)];
Item[] copy = (Item[])original.Clone();
Comparison<Item> byPriority = (x, y) => x.Priority.CompareTo(y.Priority);
Array.Sort(copy, byPriority);

Print("original", original);
Print("copy", copy);

copy[0].Name = "A*";
copy[2] = new Item("D", 40);

Print("original", original);
Print("copy", copy);

static void Print(string label, Item[] items) =>
    Console.WriteLine($"{label}: {string.Join(", ", items.Select(item => item.Name))}");

sealed class Item(string name, int priority)
{
    public string Name { get; set; } = name;
    public int Priority { get; } = priority;
}

Result

original: B, A, C
copy: A, B, C
original: B, A*, C
copy: A*, B, D

`byPriority` sorts the clone by ascending `Priority`. Changing the `Name` of `A` is visible through both arrays, but replacing `C` with `D` affects only `copy`.

Related lessons

  • C# · Lesson 43 · Intermediate · Version: 2

Sources