So here is something that came up in a discussion I was having. It revolved around delegates and their parameter types because we were trying to find an easier way to solve an issue without having to write more code than we really wanted to. If you program entirely in VB or are not using .Net framework 2.0 with C#, then you are missing out on 2 features of delegates that are very useful: covariance and contravariance. Now I have personally spent, until very recently, the vast majority of my time in VB and Framework 1.1, so even though I knew about the features, I never fully understood what I could do with them and I was never able to make use of them until now when it came up as part of a way to solve a problem in a program that I am helping a friend with. He knew nothing of these new features, so maybe there are more of you out there that benefit from this, as it doesn’t seem to be well documented in easy to find places. Just for fun I tried to google "covariance" and a few other things with no success, so maybe putting this out there will make it easier for others to find. These are fine examples of how the languages continue to evolve and allow us to create more flexible, maintainable and efficient code.
Covariance basically means that the return value of a method that is referenced by your delegate can have a different return type than that specified by the delegate itself, so long as the return type of the method is a subclass of the return type of the delegate. In the example below, you can see that MyMethod returns Car, but xyz is calling FunctionTwo, which returns type Toyota. Because Toyota is derived from Car, this works.
Contravariance is kind of the same thing, but deals with the parameters rather than return types. Contravariance allows you to use delegate parameters who’s types are those that inherit from the parameter types used in the method the delegate references. In the following example, you can see that FunctionOne specifies the Car type as the parameter, while the delegate has the signature that specifies Toyota. Contravariance allows this to happen.