Generic lists and inheritance problems

Topics: General Discussion Forum, July and December Releases Forum
Apr 4, 2008 at 10:33 AM

I have a WCF service where my data contracts inherit from a base contract:

public class CustomerContract : EntityContract, IExtensibleDataObject

In my Web Client (SF) I'm not able to do casts between List<CustomerContract> and List<EntityContract>. I dont have a clue why this give me a compile error like:

Cannot implicitly convert type 'System.Collections.Generic.List<MyCompany.Web.Service.GMB.DataContracts.CustomerContract>' to 'System.Collections.Generic.List<MyCompany.Web.Service.BPP.DataContracts.EntityContract>'

There must be some trouble with NetDataContractSerializer and generic lists because this compiles fine:

EntityContract entity = new CustomerContract();

But this don't:

List<EntityContract> entityList = new List<CustomerContract>();

I have tried ServiceKnownType(typeof(List<CustomerContract>) but I still have the same problem.
Apr 4, 2008 at 5:08 PM
Just some interesting links to take a look;

Collection Types in Data Contracts
Passing Collections Through Service Boundaries, Why and How
Sharing WCF Collection Types between Service and Client
Apr 7, 2008 at 10:04 AM
Charly, I browsed your links and I dont find it easy to find an answer on this problem. My solution was to do it this way:

List<CustomerContract> customerList = new List<CustomerContract>();
List<EntityContract> result = new List<EntityContract>(customerList.ToArray());

And by reading/browsing your links I don't understand why a List<CustomerContract> cant be cast to a List<EntityContract> just like that. The problem must be the container, the List? Do you have an answer on this in plain english?
Apr 7, 2008 at 3:53 PM
Try then this links;
Generic type parameter variance in the CLR

And further help in 'more english' terms here;
Generics Invariance An Interesting Problem
Apr 18, 2008 at 10:39 AM
Thanks Charly, the last link was very usefull. Though the two links had the same destination ;-)