A Recap
By way of recapitulation and summary, we’ve created a Dinosaur class that implements the IComparable interface
(as you can see in the class declaration):
public class Dinosaur : IComparable
The IComparable interface requires that implementing classes include a CompareTo method. I’ve done this rather
trivially, simply passing on to the class a String comparison based on the name of the class instance (see
Chapter 8 for a full explanation):
public int CompareTo (object obj) {
Dinosaur dino = (Dinosaur) obj;
return this.Name.CompareTo (dino.Name);
}
Here’s the full Dinosaur class as it stands:
public class Dinosaur : IComparable
{
private string m_Name;
public int Length = 0;
public string Name {
 get {
  return m_Name;
 }
 set {
  m_Name = value;
 }
}
public int CompareTo (object obj) {
 Dinosaur dino = (Dinosaur) obj;
 return this.Name.CompareTo (dino.Name);
}
}
In addition, we’ve got a whole bunch of derived Dinosaur classes running around:
...
class Allosaurus : Dinosaur {
public Allosaurus (string theName, int length){
 this.Name = theName;
 this.Length = length;
}
}
class TRex : Dinosaur {
public TRex (string theName, int length){
 this.Name = theName;
 this.Length = length;
}
}
...
Since they each implement IComparable—via the inherited Dinosaur class—they can be sorted in an array and
displayed in a ListBox in order:
Dinosaur [] jPark;
private void btnPoly_Click(object sender, System.EventArgs e) {
lstDino.Items.Clear();
jPark = new Dinosaur [4];
jPark[0] = new Lessemsaurus("lessaemsaurus", 7);
jPark[1] = new Allosaurus("allosaurus", 12);
jPark[2] = new TRex("tRex", 14);
jPark[3] = new Diplodocus("doc", 9);
Array.Sort (jPark); // sort uses IComparable
foreach (Dinosaur dino in jPark){
 lstDino.Items.Add(dino.Name);
}
}
|
|
Search Engine Optimization
 
Syndication Viewer
Our Web host:
IX WebHosting
|