Contrawhatywho – nicer generics in C# 4.0

Everyone probably knows this already, but it’s probably easy to miss as *stuff now just works*. Contravariance, or covariance is now improved to make working with generics that little bit simpler.

The following code now compiles fine in .net 4, but won’t compile against .net 3.5:

class Program
{
static void Main(string[] args)
{
Animal a = new Animal();
Bear b = new Bear();
IList<Bear> bears = new List<Bear>();
bears.Add(b);
IEnumerable<IAnimal> animals = bears;
}

class Animal : IAnimal
{
public override string ToString()
{
return “I am an animal”;
}
}

   class Bear : IAnimal
   {
       public override string ToString()
       {
           return "I am a bear";
       }
    } 

    internal interface IAnimal
    {
    }
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
This entry was posted in Uncategorized. Bookmark the permalink.