Hi Wal,

 

With the release of .NET 4.0 the framework introduced co-variance &
contra-variance on collection types. What you're trying to do is
co-variance. This says that if `Order` can be assigned to `IOrder` then so
too can `IEnumerable<Order>` be assigned to `IEnumerable<IOrder>`. Prior to
.NET 4.0 you could not do this with collections.

 

On the other hand, arrays have had co-variance and contra-variance since
.NET 1.0. So you can assign arrays in the way that you showed.

 

The danger with co-variance of arrays is that you can cast an array of
string to an array of object and then proceed to assign any type of object
(say an int or a `Foo`) to the array resulting in a run-time error.

 

The .NET 4.0 co-variance/contra-variance of collections avoids this danger
by allowing casting to a read-only IEnumerable<T> interface rather than to
List<T>.

 

I hope this helps.

 

Cheers.

 

James.

 

From: [email protected] [mailto:[email protected]]
On Behalf Of Wallace Turner
Sent: Thursday, 12 August 2010 18:01
To: 'ozDotNet'
Subject: converting List<T> into IEnumerable<InterfaceT>

 

Hi,

Assume the class definitions

interface IOrder { }

class Order : IOrder { }

 

I understand why this doesn't compile:

 

var list = new List<Order>();

IEnumerable<IOrder> iOrders = list; //IEnumerable<IOrder> not same type as
List<Order>!

 

So using that logic, can't understand why this *does* compile:

 

var arr = new Order[0];

IEnumerable<IOrder> iOrders = arr; //IEnumerable<IOrder> assignable from
Order[] ?

 

Cheers,

 

Wal

Reply via email to