Exercise Solutions: Interfaces and Polymorphism

Line numbers are for reference. They may not match your code exactly.

Sorting Flavors by Cones by Cost

  1. Create the new class ConeComparer.
  2. Implement the IComparer interface and evaluate Cone objects by cost
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   public class ConeComparer : IComparer<Cone>
   {
      public ConeComparer()
      {
      }

      public int Compare(Cone x, Cone y)
      {
         double diff = x.Cost - y.Cost;
         if(diff == 0)
         {
            return 0;
         }
         else if (diff < 0)
         {
            return -1;
         }
         else
         {
            return 1;
         }
      }
   }

Back to exercises

  1. In the Main() method, sort the availableCones list, then print the elements to the screen to verify the results.
1
2
3
4
5
6
   ConeComparer compareCones = new ConeComparer();
   availableCones.Sort(compareCones);
   foreach (Cone c in availableCones)
   {
      Console.WriteLine(c);
   }

Back to exercises