tags:

views:

80

answers:

2

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?

A: 

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.

Spence
See my comment to Jared - there's no such thing as C# 3.5.
Jon Skeet
Arg, reminds me of the beauracrat in Futurama.Although that said Linq WAS a language change, and was not introduced till C# 3.5, so C# was 2.0 until it was given the linq extensions, WCF was simply a framework upgrade in 3.0.
Spence
+2  A: 

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.

JaredPar
@itowlson, this is what the user is doing in the sample. They didn't specify the Add behavior was a part of the desired solution.
JaredPar
You mean .NET 3.5, not C# 3.5.
Jon Skeet