Comparison<'T> Delegate


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Represents the method that compares two objects of the same type.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

type Comparison<'T> = 
    delegate of 
        x:'T *
        y:'T -> int


Type: T

The first object to compare.

Type: T

The second object to compare.

Return Value

Type: System.Int32

A signed integer that indicates the relative values of x and y, as shown in the following table.



Less than 0

x is less than y.


x equals y.

Greater than 0

x is greater than y.

Type Parameters


The type of the objects to compare.

This delegate is used by the Sort<'T>('T[], Comparison<'T>) method overload of the Array class and the Sort(Comparison<'T>) method overload of the List<'T> class to sort the elements of an array or list.

The following code example demonstrates the use of the Comparison<'T> delegate with the Sort(Comparison<'T>) method overload.

The code example defines an alternative comparison method for strings, named CompareDinosByLength. This method works as follows: First, the comparands are tested for null, and a null reference is treated as less than a non-null. Second, the string lengths are compared, and the longer string is deemed to be greater. Third, if the lengths are equal, ordinary string comparison is used.

A List<'T> of strings is created and populated with four strings, in no particular order. The list also includes an empty string and a null reference. The list is displayed, sorted using a Comparison<'T> generic delegate representing the CompareDinosByLength method, and displayed again.

No code example is currently available or this language may not be supported.

The following example uses the Comparison<'T> delegate to sort the elements of a collection of CityInfo objects. CityInfo is an application-defined class that contains information about a city and its population. The example defines three methods, CompareByName, CompareByPopulation, and CompareByNames, that offer three different ways of ordering the CityInfo objects. Each method is assigned to the comparison argument of the Array.Sort<'T>('T[], Comparison<'T>) method.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top