Search code examples
c#oopinheritanceparent-child

Convert List of Base Class to a List of Derived Class - possible?


I coworker of mine told me that it was possible to convert a List<BaseClass> to a List<DerivedClass> (they didn't show me a working example). I didn't think it was possible to convert a parent class into a child class (I do know however that it is possible to do it the other way around). I've seen several related questions with people saying it can't be done and people saying it can - none of the proposed solutions have worked for me at all. I always get a:

System.InvalidCastException.
Unable to cast object of type 'BaseClass' to 'ChildClass'

Is this absolutely possible? If so, what am I doing wrong? Here is my code (simplified for the purposes of this question):

Parent class:

public class ParentClass
{
    public string Name = "";
}

Child class:

public class ChildClass: ParentClass
{
    public string Date = "";
}

Converting:

List<ParentClass> parentList = ServiceApi.GetParentClassList().ToList();
List<ChildClass> childList = parentList.Cast<ChildClass>().ToList();

My actual code is significantly more complex but the same principles should apply.


Solution

  • Cast<T> method applies cast operation to all elements of the input sequence. It works only if you can do the following to each element of the sequence without causing an exception:

    ParentClass p = ...
    ChildClass c = (ChildClass)p;
    

    This will not work unless p is assigned an instance of ChildClass or one of its subclasses. It appears that in your case the data returned from the server API contains objects of ParentClass or one of its subclasses other than ChildClass.

    You can fix this problem by constructing ChildClass instances, assuming that you have enough information from the server:

    List<ChildClass> childList = parentList
        .Select(parent => new ChildClass(parent.Name, ... /* the remaining fields */))
        .ToList();