Possible Duplicate:
Upcasting and generic lists
Ok, I want to send a List<CardHolder> as an IEnumerable<ICardHolder> where CardHolder : ICardHolder. However, the compiler errors:
Error 4 Argument ‘1’: cannot convert from ‘System.Collections.Generic.List’ to ‘System.Collections.Generic.IEnumerable’
This seems strange to me, considering that an List<T> : IEnumerable<T>. What’s going wrong?
public interface ICardHolder
{
List<Card> Cards { get; set; }
}
public class CardHolder : ICardHolder
{
private List<Card> cards = new List<Card>();
public List<Card> Cards
{
get { return cards; }
set { cards = value; }
}
// ........
}
public class Deck : ICardHolder
{
// .........
public void Deal(IEnumerable<ICardHolder> cardHolders)
{
// ........
}
// .........
}
public class Game
{
Deck deck = new Deck();
List<CardHolder> players = new List<CardHolder>();
// .........
deck.Deal(players); // Problem is here!
// .........
}
The problem is that
List<T>is not a subtype ofIEnumerable<T1>even ifT : T1.Generics in C# (before C# 4.0) are ‘invariant’ (ie. don’t have this sub-typing relationship). In .Net 4,
IEnumerable<T>will have its type parameter annotated as being ‘covariant’. This means thatList<T>will be a subtype ofIEnumerable<T1>ifT : T1.See this page on MSDN for more details of this feature.
Edit – You can work around this in your case by making the
Dealmethod generic: