System.Collections.Comparer Class
The Comparer
class provides a way to compare two objects of a particular type, using the IComparable
interface or a supplied IComparer
implementation. It is commonly used with collections that require sorting.
Namespace
System.Collections
Assembly
mscorlib.dll
Inheritance
- System.Object
- System.Collections.Comparer
Syntax
public sealed class Comparer : IComparer
Constructors
Signature | Description |
---|---|
Comparer() |
Initializes a new instance of the Comparer class that uses the current culture. |
Comparer(CultureInfo culture) |
Initializes a new instance that uses the specified CultureInfo . |
Properties
Property | Type | Description |
---|---|---|
Default |
Comparer |
Gets a default comparer that uses the current culture. |
Methods
Signature | Returns | Description |
---|---|---|
int Compare(object x, object y) |
int |
Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. |
static Comparer Create(IComparer comparer) |
Comparer |
Creates a new Comparer that uses the supplied IComparer implementation. |
Example
// Sorting an ArrayList using the default Comparer
using System;
using System.Collections;
using System.Globalization;
class Demo
{
static void Main()
{
ArrayList list = new ArrayList
{
"orange",
"Apple",
"banana",
"Cherry"
};
// Sort using the case‑insensitive comparer for the current culture
list.Sort(Comparer.Default);
foreach (string s in list)
Console.WriteLine(s);
}
}
Remarks
The Comparer
class is primarily used by non‑generic collections that require an IComparer
implementation, such as ArrayList.Sort
or SortedList
. For generic collections, consider using System.Collections.Generic.Comparer<T>
instead.