e.g.:
C#
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!
Answers
Know the answer? Post it. Somebody with the same question will find it here.