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.
Assembly: mscorlib (in mscorlib.dll)
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::Int32A 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.
Note: |
|---|
To run this example, see Building examples that have static TextBlock controls for Windows Phone 8. |
Note: