6
Answers

NP92 CompareTo()

Maha

Maha

16y
5.5k
1

Hi Guys

 

NP92 CompareTo()

 

Following program is executing well. I couldn’t understand the logic behind the CompareTo(). Anyone knows please explain.

 

Thank you

 

using System;

 

namespace ObjComp

{

   // The iteration of the Car can be ordered

   // based on the CarID.

   public class Car : IComparable

   {

      // State data.

      private int CarID;

      private string petName;

 

      // properties.

      public int ID

      {

         get { return CarID; }

         set { CarID = value; }

      }

      public string PetName

      {

         get { return petName; }

         set { petName = value; }

      }

 

      // Constructor set.

      public Car(int id, string name)

      {

         this.CarID = id;

         this.petName = name;

      }

 

      // IComparable implementation.

      int IComparable.CompareTo(object o)

      {

         Car temp = (Car)o;

         if (this.CarID > temp.CarID)

            return 1;

         if (this.CarID < temp.CarID)

            return -1;

         else

            return 0;

      }

   }

 

   public class CarApp

   {

      public static int Main(string[] args)

      {

         // Make an array of Car types.

         Car[] myAutos = new Car[5];

         myAutos[0] = new Car(123, "Rusty");

         myAutos[1] = new Car(6, "Mary");

         myAutos[2] = new Car(6, "Viper");

         myAutos[3] = new Car(13, "NoName");

         myAutos[4] = new Car(6, "Chucky");

 

         // Now, sort them using IComparable.

         Array.Sort(myAutos);

 

         // Dump sorted array.

         Console.WriteLine("***** Here is the ordered set of cars *****");

         foreach (Car c in myAutos)

            Console.WriteLine("{0} {1}", c.ID, c.PetName);

 

         return 0;

      }

   }

}

/*

***** Here is the ordered set of cars *****

6 Chucky

6 Mary

6 Viper

13 NoName

123 Rusty

*/

Answers (6)