×

c# · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

tells Sort which object comes first.

.Sort() knows how to order numbers and text, but not your own objects. Is a kite bigger than a robot? You decide, by implementing the built-in interface IComparable<Toy>, which promises one method: .

a.CompareTo(b) gives a negative number when a comes first, zero when they tie, and a positive number when b comes first. Numbers and strings have their own CompareTo, so Price.CompareTo(other.Price) orders toys from cheapest to dearest.

Call .Sort() on a list of objects with no IComparable, and it stops with InvalidOperationException.

using System;
using System.Collections.Generic;

var toys = new List<Toy> { new Toy("kite", 8), new Toy("yo-yo", 2), new Toy("robot", 25) };
toys.Sort();
Console.WriteLine($"{toys[0].Name}, {toys[1].Name}, {toys[2].Name}");

class Toy : IComparable<Toy>
{
    public string Name { get; set; }
    public int Price { get; set; }
    public Toy(string name, int price)
    {
        Name = name;
        Price = price;
    }
    public int CompareTo(Toy other) { return Price.CompareTo(other.Price); }
}

Swap the two sides, other.Price.CompareTo(Price), and the order flips.