compare

Summary

Defines how objects can be compared.

Usage

Comparison compare(T obj)

Parameters

obj

The object to compare to.

Description

Defines how objects can be compared (with a "less than", "greater than", or "equal to" relationship).

Only objects that can be compared can be sorted.

Examples

Comparison of Employees by Age
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
import System;
 
class Employee : IComparable<Employee>
{
    private unsigned int age;
    private string firstName;
    private string lastName;
 
    public Employee(string firstName, string lastName, unsigned int age) {
        this.firstName = firstName;
        this.lastName  = lastName;
        this.age       = age;
    }
 
    public Comparison compare(Employee that) {
        // Sort by employee age using System.UInteger32.compare
        return this.age.compare(that.age);
    }
}
 
Employee john = new Employee("John", "Smith", 52);
Employee jane = new Employee("Jane", "Doe", 32);
 
if (john.compare(jane) == Comparison.GREATER_THAN) {
    Console.log("John is older than Jane.");
}

Share

HTML | BBCode | Direct Link