Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of objects to List of interfaces

Tags:

c#

.net

.net-3.5

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?

like image 994
leora Avatar asked Jan 04 '10 05:01

leora


2 Answers

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.

like image 90
JaredPar Avatar answered Nov 15 '22 06:11

JaredPar


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...

like image 8
Ramin Bateni Avatar answered Nov 15 '22 05:11

Ramin Bateni