Casting typed collections

Jun 14 2006 11:06 AM
Hello everybody! I have come upon a problem when using typed lists in .Net 2.0: it is impossible to cast a list of an implementing type to a list typed to the implemented interface.
e.g.:
 

class Program

{

static void Main(string[] args)

{

List<Banana> bananas = new List<Banana>();

List<IFruit> fruitsFail = bananas; //Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<CastExample.Banana>' to 'System.Collections.Generic.List<CastExample.IFruit>'

List<IFruit> fruitsWork = new List<IFruit>();
foreach (Banana b in bananas)

fruitsWork.Add(b);

}

}

interface IFruit { }

class Apple : IFruit { }

class Banana : IFruit { }

As you see i am able to iterate through the collection and cast every element to build a new list. Can somebody tell a more elegant way to get a list typed to the interface or point to my error in reasoning? Thanks a lot!