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?
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With