Order Comparison
Protocols are:
1. The IComparable Interfaces
2. The < and > Operators
IComparable Interfaces
Used for general-purpose sorting algorithms.
System.String implements IComparable interfaces.
string[] colors = { "Green", "Red", "Blue" }; Array.Sort (colors); foreach (string c in colors) Console.Write (c + " "); // Blue Green Red // The IComparable interfaces are defined as follows: // public interface IComparable { int CompareTo (object other); } // public interface IComparable{ int CompareTo (T other); } Console.WriteLine ("Beck".CompareTo ("Anne")); // 1 Console.WriteLine ("Beck".CompareTo ("Beck")); // 0 Console.WriteLine ("Beck".CompareTo ("Chris")); // -1
If a comes after b, a.CompareTo(b) returns a positive number.
If a is the same as b, a.CompareTo(b) returns 0.
If a comes before b, a.CompareTo(b) returns a negative number.
< and > Operators
The < and > operators are more specialized and mostly used for numeric types. They are efficient for bytecode translation and used for intensive algorithms.
// Some types define < and > operators: bool after2010 = DateTime.Now > new DateTime (2010, 1, 1); // The string type doesn't overload these operators (for good reason): bool error = "Beck" > "Anne"; // Compile-time error
public struct Note : IComparable, IEquatable , IComparable { int _semitonesFromA; public int SemitonesFromA => _semitonesFromA; public Note (int semitonesFromA) { _semitonesFromA = semitonesFromA; } public int CompareTo (Note other) // Generic IComparable { if (Equals (other)) return 0; // Fail-safe check return _semitonesFromA.CompareTo (other._semitonesFromA); } int IComparable.CompareTo (object other) // Nongeneric IComparable { if (!(other is Note)) throw new InvalidOperationException ("CompareTo: Not a note"); return CompareTo ((Note) other); } public static bool operator < (Note n1, Note n2) => n1.CompareTo (n2) < 0; public static bool operator > (Note n1, Note n2) => n1.CompareTo (n2) > 0; public bool Equals (Note other) // for IEquatable => _semitonesFromA == other._semitonesFromA; public override bool Equals (object other) { if (!(other is Note)) return false; return Equals ((Note) other); } public override int GetHashCode() => _semitonesFromA.GetHashCode(); public static bool operator == (Note n1, Note n2) => n1.Equals (n2); public static bool operator != (Note n1, Note n2) => !(n1 == n2); } static void Main() { Note n1 = new Note (1); Note n2 = new Note (2); (n2 > n1).Dump(); }