Search code examples
c#wcftype-conversiondatacontractserializer

Cast issues between generic list and CollectionDataContract


I have the following collection contract defined:

[CollectionDataContract(Name = "Centres")]
public class Centres : List<Centre>
{}

and the following operation contract defined to return this collection

public Model.Centres GetCentres()
{
     List<Centre> allCentres = (from c in Model.Centre.GetCentres()
                                    where c.Visible == true
                                    select c).ToList();

     return allCentres
}

But when I run the code I receive an ExplicitCastException. So as far as I can see I'm trying to cast a list of centres (List) into my collection 'Centres' which itself derives from List. Is this possible or by deriving a new object am I creating a new type of list that won't work in this way.

My current work around for this problem is to declare a new instance of Centres and copy all centres into it using a foreach.


Solution

  • The problem is Centres "is a" List<Centre>, List<Centre> is not a Centres.

    Despite Centres having no implementation it is still a sub-class of List<Centre>, you could extend your Centres class to have an implicit conversion operator or, perhaps add a constructor to Centres that takes a List<Centre> as a parameter.

    Try changing Centres to somthing like ...

    [CollectionDataContract(Name = "Centres")] 
    public class Centres : List<Centre> 
    {
        public static implicit operator Centres(List<Centre> l)
        {
            Centres newCentres = new Centres();
            newCentres.AddRange(l);
            return newCentres;
        }
    }
    

    Then it will allow implicit conversion from List<Centre>.