Braintique.com header
Left Navigation Bar

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.

Object Browser

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.

Results

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