Generic Variance Baby!

by Ben Hart 13. November 2008 15:40

I've been pretty busy lately. The day job is getting interesting, as are a few side projects. A lot has happened the last few weeks, both in my world, and the larger .NET'o'sphere. I haven't had much time to write to this blog, but I've made an effort to keep up with others.

What I'm still most excited by (yes, it's been a few weeks of heightened heart-rate) is the introduction of generic variance in C#. I don't care to admit how many times I've written something along the lines of the following:

public void DoSomething()
{
    IList<Child> children = new List<Child>();
    IList<Parent> parents = children;
}
class Parent{}
class Child : Parent{}

The above invalidity is obvious (after the first time, at least), but more subtle variations continue to catch me (lambdas spring to mind). It seems so intuitive to be able to assign a generic type of a subclass to that of a superclass. I've occasionally refactored to a point relying on something along these lines, before pulling up the handbrake (or is that the shift to reverse?) when the compiler reminds me it's not valid.

GVAvatarBut no longer. Well, at least, soon no longer... C# 4.0 introduces generic variance.

I'm not going to add anything to what's already been written. My only contribution is my little friend on the left here - lovingly created to celebrate the occasion. He represents the wonderful diversity in code that will soon be possible. (Except the t-shirt. That's chosen because a friend of mine played with My Little Ponies as a boy, so that's for him.)

If you want to learn more about generic variance, and be casually able to drop the terms covariant and contravariant into the standup tomorrow morning, Nate Kohari has a great summary in this post. Alternatively, download the CTP of VS2010, and shake up that invariance...

Technorati Tags: ,,,,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | C#

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About me...

I'm a passionate .NET developer, with C# my language of choice. I've been at it for a number of years now, and enjoy that I'll never shake the feeling I'm just starting out.

I love software, and I love building it even more. I love knowing that my work facilitates others', and that one line of code at a time, we're increasing our capability.

More...



Page List