Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Comparison<T> — a delegate defining sort order

Comparison<T> in System describes a function comparing two values of type T. It returns an int whose sign determines their order; this delegate can be passed to List<T>.Sort.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

// This assignment compiles without a constraint on T.
// Comparer<T>.Default can use a value's runtime IComparable implementation
// even if T itself does not implement IComparable. If the default comparer
// cannot order the supplied values, invoking the delegate can throw.
Comparison<T> comparison = (x, y) => System.Collections.Generic.Comparer<T>.Default.Compare(x, y);

Comparison<T> is a delegate type in System: it accepts x and y of type T and returns an int. A result < 0 places x before y, 0 means the same position in the ordering, and a result > 0 places x after y. The sign matters, not the specific values -1 and 1.

List<T>.Sort(Comparison<T>) accepts this rule and sorts the existing list. The delegate describes a pairwise comparison—it is not itself a sorting algorithm. Comparing an element with itself must return 0; an invalid rule can cause an exception during sorting. The sort is not stable: elements that compare as equal need not retain their original order.

In the example, y.CompareTo(x) reverses the usual numeric order, producing descending order. CompareTo returns a result matching the comparison contract. After numbers.Sort(descending), the expected output is 3, 2, 1.

Examples

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var numbers = new List<int> { 3, 1, 2 };
        Comparison<int> descending = (x, y) => y.CompareTo(x);

        numbers.Sort(descending);
        Console.WriteLine(string.Join(", ", numbers));
    }
}

Result

3, 2, 1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources