Search code examples
c#genericsinheritancepoco

If object O inherits from object T, how can I convert List<O> to List<T>?


I have a JSON response that depends on a POCO C# object I can't directly modify. I need to add some fields to the POCO object, and then mask them from any other component of the application that reuses the same object.

Since I control both the webserver, and the client, (but not the POCO object itself), My solution is to derive from the object T, creating List<O>, and then convert that to List<T> for any dependency that doesn't want to see my additions within derived object O.

If T is a parent of O, and simple casting doesn't work, how should I convert from one to the other?

e.g.

public class Parent
{
  public string ParentString {get;set;}
}

public class Child : Parent
{
   public string ChildTempObject {get;set;}
}


public static DoStuff()
{
   List<Child> childList = new List<Child>
   //... get from webservice...
   return (List<Parent>)childList; // doesn't work
}

Solution

  • Use Enumerable.Cast<T>:

    List<Parent> parentList = childList.Cast<Parent>().ToList();