Braintique.com header
Left Navigation Bar

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);
}
}

ListBox

Previous Table of Contents Next


Google
 
Web www.braintique.com
www.digitalfieldguide.com www.googleplexblog.com


Home | Barticles | Blogs | Books | Services | FAQ | Contact

© Braintique.com. All rights reserved.

Search Engine Optimization







RSS 2.0 Syndication feed

Syndication Viewer

Our Web host:
IX WebHosting



Food for Your Brain! Get a Barticle! Questions Answered Books for You What We Can Do For You Contact Us Brain Food Questions Answered Books for You What We Can Do For You Frequently Asked Questions About Us Google Research Photoshop Wi-Fi and Wireless Networking The Natural Way to Write