So although I've been heads down, I have noticed that .NET 4.0 and the latest Visual Studio 2010 CTP have been released. There are alot of great things coming but one which may cause a little confusion based on it's name is CoVariance. Both C# and VB are getting CoVariance but what does that mean. Well let's start with generics. When teaching I like to introduce generics by saying “OK now this feature is called ‘generics’ but it’s all about specifics.” I then discuss how polymorphism allows us to generically handle an object but how that can introduce two issues (1. minor is boxing 2. major is loss of type checking - since everything is an object) What ‘generics’ allow us to do is to tell the compiler which specific type will be in a collection and that resolves both of those issues in our benefit. This is an abreviation of a full explanation and added simply to place CoVariance in context, since it deals strictly with generics.
Unfortunately one of the challenges with generics is that you can cast a List<string> into a method thats looking for a list of objects list<integer> and just allow the code to run against whichever generic collection containing either strings or ints you pass in. Now, even in VB6 it was not uncommon to have several different buttons connected to the same event handler. In fact if you have a grid or similar construct with embedded controls this is still a common pattern, where the event handler is told which row the event came from. The reason is very simple, each row will have a similar piece of code that differs only by which row should be impacted and you wouldn’t want to rewrite that code.
Similarly, you probably have several different collections each of which is associated with a specific type through a generic declaration. There will be certain actions that you want to take on any of those different specific collections. This new feature allows you to define a single method and tell it to execute on any of the generic collections which support it’s expected interface. The idea is you can have a single copy of your code that knows how to work generically with the different collections associated with different specific types, that you will pass it. The good news is the compiler can see the type information for every planned access and even do type checking for each different type, thus you get the power of a polymorphic object with all the compiler based safety of strong typing.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.