Implementing the ICarnivore Interface
To actually implement ICarnivore means to add an appropriate CanIEatU method to the Dinosaur class (from
which all the other classes inherit).
I’ve used the Dinosaur class Length field to go with something pretty simple: If I’m longer than you, I can eat
you. Here’s how this code looks:
public bool CanIEatU (object obj){
Dinosaur dino = (Dinosaur) obj;
if (this.Length > dino.Length)
 return true;
   else
 return false;
}
Here’s the complete Dinosaur class, implementing both IComparable and ICarnivore:
public class Dinosaur : IComparable, ICarnivore
{
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);
}
public bool CanIEatU (object obj){
 Dinosaur dino = (Dinosaur) obj;
 if (this.Length > dino.Length)
  return true;
 else
  return false;
}
}
It’s sometimes helpful to use the Object Browser to display the interfaces implemented by a class—which
includes custom interfaces such as ICarnivore.
Once you implement an interface, it’s easy to use its functionality—because, according to “contract,” you
know the functionality is going to be there.
For example, you can create two dinosaurs, see who is going to eat whom for dinner using a class instance’s
CanIEatU method, and display the results:
private void btnICarnivore_Click(object sender, System.EventArgs e) {
lstDino.Items.Clear();
TRex chomper = new TRex ("Chomper", 14);
Allosaurus ally = new Allosaurus ("Ally", 12);
if (chomper.CanIEatU (ally)){
 lstDino.Items.Add (chomper.Name + " the " +
 chomper.GetType().ToString());
lstDino.Items.Add ("has eaten");
lstDino.Items.Add (ally.Name + " the " +
 ally.GetType().ToString());
lstDino.Items.Add ("for dinner.");
}
}
As you can see from these two articles, implementing existing .NET interfaces is a good way to make sure
that your classes are deployed with standardized functionality that other developers expect.
In addition, implementing your own interfaces is an excellent way to enforce best practices and standardized
development across a team—likely with more functionality than the Dinosaur classes shown in the tutorials in
this article.
|