Given the following LinqPad example:
void Main()
{
List<DbItem> dbItems = new List<DbItem>
{
new DbItem{Id = 4, SomeValue = "Value For 4", OtherValue = 1},
new DbItem{Id = 19, SomeValue = "Value For 19", OtherValue = 2}
};
ListMethod(dbItems.Cast<IDbItem>().ToList()); <-+
EnumerableMethod(dbItems); <-+
} |
|
// These are the methods are I asking about -------+
public void ListMethod(List<IDbItem> dbItems)
{
Console.WriteLine(dbItems);
}
public void EnumerableMethod(IEnumerable<IDbItem> dbItems)
{
Console.WriteLine(dbItems);
}
public class DbItem : IDbItem
{
public int Id {get; set;}
public string SomeValue {get; set;}
public int OtherValue {get; set;}
}
public interface IDbItem
{
int Id {get; set;}
string SomeValue {get; set;}
}
Why can EnumerableMethod
take the list directly while ListMethod
needs a cast first?
I get that an cast is happening from DbItem to IDbItem, but what is different about the IEnumerable that allows it to make the cast without an express request?
I imagine the answer involves the word Covariance, but I don't know enough about that to just figure it out myself.