Comparison(T) Delegate
TOC
Collapse the table of content
Expand the table of content

Comparison<T> Delegate

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

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

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

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

Type Parameters

in T

The type of the objects to compare.

This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see [2678dc63-c7f9-4590-9ddc-0a4df684d42e].

Parameters

x
Type: T
The first object to compare.
y
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.

Value

Condition

Less than 0

x is less than y.

0

x equals y.

Greater than 0

x is greater than y.

This delegate is used by the Sort<T>(array<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 nullptr, 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.

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2017 Microsoft