leora
leora

Reputation: 196469

Convert List of objects to List of interfaces

if i have objectA that implements ISomeInterface

why can't i do this:

List<objectA> list = (some list of objectAs . . .)

List<ISomeInterface> interfaceList = new List<ISomeInterface>(list);

why can't i stick in list into the interfaceList constructor ? Is there any workaround?

Upvotes: 21

Views: 14618

Answers (3)

Ramin Bateni
Ramin Bateni

Reputation: 17415

Easiest & shorter way is:

var interfaceList = list.Cast<ISomeInterface>().ToList()

OR

List<ISomeInterface> interfaceList = list.Cast<ISomeInterface>().ToList()

Both above sample codes are equal and you can use each one you want...

Upvotes: 10

JaredPar
JaredPar

Reputation: 754665

In C# 3.0 + .Net 3.5 and up you can fix this by doing the following

List<ISomeInterface> interfaceList = new List<ISomeInterface>(list.Cast<ISomeInterface>());

The reason why this doesn't work is that the constructor for List<ISomeInterface> in this case takes an IEnumerable<ISomeInterface>. The type of the list variable though is only convertible to IEnumerable<objectA>. Even though objectA may be convertible to ISomeInterface the type IEnumerable<objectA> is not convertible to IEnumerable<ISomeInterface>.

This changes though in C# 4.0 which adds Co and Contravariance support to the language and allows for such conversions.

Upvotes: 36

Spence
Spence

Reputation: 29332

This is dealt with in C# 4.0, you cannot do this in C# 3.5 directly. You can create a new list from this list however and use an extension operator or foreach to do it cleanly, albeit slower than a cast to the type which will be provided by covariance contravariance (always get these wrong) in C# 4.

Upvotes: 2

Related Questions