Testing Contravariant and Covariant Methods

The .NET Framework version 4.0 supports a new programming language feature called variant methods. Let me cut to the chase and state I think variant methods are an example of solutions in search of a problem, but they’re fascinating anyway. So what are contravariant and covariant methods, and how do you test them? In order to test variant methods you need to understand what they are. In short, MSDN Library documentation states that contravariance is the ability to use a less derived type, and covariance is the ability to use a more derived type than that originally specified. My initial reaction was pretty much WTH (what the heck). I couldn’t entirely follow the MSDN examples so I played around with some code myself. After some experimentation, I believe that the scenario where contravariance and covariance are most likely to be used is when you 1.) have a generic interface, and also 2.) have a base class which implements the generic interface, and also 3.) a second class which is derived from / inherits from the base class. For example, suppose you have some generic interface IConsoleDisplayable<T>:
 
public interface IConsoleDisplayable<T>
{
  . . .
}
and a class Person which implements IConsoleDisplayable<>, and also a class Employee which is derived from class Person. Without contravariance and covariance the following code does not work:
 
IConsoleDisplayable<Person> p = new Person("Smith", "Chris"); // OK
. . .
IConsoleDisplayable<Employee> e = p; // error
 
and requires an explicit cast like this:
 
IConsoleDisplayable<Employee> e = (IConsoleDisplayable<Employee>)p; // OK
 
But if you declare the generic interface as contravariant by adding the "in" keyword like this:
 
public interface IConsoleDisplayable<in T>
{
  . . .
}
 
then the code above (without an explicit cast) compiles. Well this is just plain psycho on a variety of levels and seems like the C# language team had way too much time on their hands. Just because you can create some new language feature doesn’t necessarily mean you should. (Of course, there’s no reason why application or system developers have to use variant methods). In my opinion, the advantage gained by eliminating an explicit cast is not worth the additional complexity of a contravariant interface. But it’s an interesting language concept for sure.
 
This entry was posted in Software Test Automation. Bookmark the permalink.