none
Can't understand why this won't work RRS feed

  • Question

  • I have the following:

    Class A { //some members }

    [CollectionDataContract]

    Class CollectionA: List<ClassA>{} //code block

    var listA = EntityModel.Table.Select(x => new Class A { /* yada yada*/}).ToList(); var colA = (CollectionA)listA;


    The cast at the end fails.  Why and how do I fix it.

    Monday, August 12, 2013 1:50 PM

Answers

  • You are trying to do a downcasting, i.e. take a List<ClassA> base class and try and turn it into a more specific CollectionA class. This is illegal unless the object is already a derived object but the variable holding it is of the base class type:

    BaseClass b = new DervivedClass();
    DervivedClass d = (DervivedClass)b;

    You could solve the problem by initialize the base class in the constructor of the CollectionA class:

    public class CollectionA: List<ClassA>
    {
      public CollectionA(IEnumerable<ClassA> list)
        : base(list) {
       
    }
    var listA = EntityModel.Table.Select(x => new Class A { /* yada yada*/}).ToList();
    CollectionA cola = new CollectionA(listA);

     

     

    Monday, August 12, 2013 2:20 PM