Last week, I had the honor and pleasure of teaching an Advanced C++ class at ExxonMobil in Houston, Texas. All of the students were brilliant and were employees in their Research division. I think I was the only one there without a PhD. In fact, several of them, had multiple doctorates or post-doctorates… which I didn’t even know existed.
But I digress. Since I hadn’t taught that class in about a decade and hadn’t used C++ professionally since circa 2003, my brain pushed a lot of my C++ knowledge out into its proverbial “garage” for later retrieval. After several days of submersion in the language and C++ labs, we finally got to some clever inheritance problems and polymorphism tricks. That brought back my long, lost memory of “Capability Classes and Capability Queries”.
While not exactly rocket science, Capability Queries can be of use in C# as well as C++. So here is what a capability class looks like… well, wait, let’s lay sound ground work first:
public class Animal { }
public class WarmBloodedAnimal : Animal { }
public class Human : WarmBloodedAnimal { }
public class Bird : WarmBloodedAnimal { }
Nothing really special there is there? Both birds and a humans are warm-blooded animals. So what?!
What if we had a collection of animals… say, just for arguments sake, a List
public void SomeRandomMethod(IList<Animal> animals_)
{
foreach (var animal in animals_)
if (animal is Bird)
(animal as Bird).Fly();
}
But, what about birds that can’t fly?! Penguins can’t fly but they’re excellent swimmers. Should we add an attribute to the Animal base class for “IsCapableOfFlight”? I think not. Why pollute the interface and thusly pollute every derived class with that attribute!?!
That brings us to Capability Classes (Interfaces in C#).
public interface CapableOfFlight
{
public void Fly();
}
public class Eagle : Bird, CapableOfFlight { }
public class Parakeet : Bird, CapableOfFlight { }
public class Ostrich : Bird { }
public class Penguin : Bird { }
public void SomeRandomMethod(IList<Animal> animals_)
{
foreach (var animal in animals_)
if (animal is CapableOfFlight)
(animal as CapableOfFlight).Fly();
}
Obviously, it would be awesome to use LINQ to do a query on that collection with a ‘where’ clause that used the “animal is CapableOfFlight” but just by itself… it’s quite nice.
Go green… don’t pollute your interfaces and keep your derived/implementer classes skinny!

I came to 








