IComparable<T>

Summary

Implementing the IComparable<T> interface allows objects to be compared and sorted.

Description

Implementing the IComparable<T> interface allows objects to be compared to other objects.

If IComparable<T> is implemented for a class and T is the same type as the class inheriting from IComparable, objects of the class type become sortable (e.g. using System.Array<T>.sort).

Examples

Making a Class Sortable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import System;
 
class Employee : IComparable<Employee>
{
    private string firstName;
    private string lastName;
 
    public Employee(string firstName, string lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    public Comparison compare(Employee that) {
        // Sort by employee last name using System.String.compare
        return this.lastName.compare(that.lastName);
    }
 
    public override string toString() {
        return this.firstName + " " + this.lastName;
    }
}
 
Employee zig  = new Employee("Zig", "Ziglar");
Employee john = new Employee("John", "Smith");
Employee abe  = new Employee("Abe", "Lincoln");
 
Employee[] employees = [ zig, john, abe ];
employees.sort();
Console.log(employees.join(", "));
 
// Output:
// Abe Lincoln, John Smith, Zig Ziglar

Methods

  • compare

    Defines how objects can be compared.

Share

HTML | BBCode | Direct Link