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
The reason why this doesn’t work is that the constructor for
List<ISomeInterface>in this case takes anIEnumerable<ISomeInterface>. The type of the list variable though is only convertible toIEnumerable<objectA>. Even thoughobjectAmay be convertible toISomeInterfacethe typeIEnumerable<objectA>is not convertible toIEnumerable<ISomeInterface>.This changes though in C# 4.0 which adds Co and Contravariance support to the language and allows for such conversions.