0

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
}
Ran Dom
  • 315
  • 5
  • 13

2 Answers2

2

Use Enumerable.Cast<T>:

List<Parent> parentList = childList.Cast<Parent>().ToList();
adjan
  • 13,371
  • 2
  • 31
  • 48
  • `OfType` vs `Cast` is discusssed [here](https://stackoverflow.com/questions/4015930/when-to-use-cast-and-oftype-in-linq) –  May 16 '19 at 15:06
1

You can use the following to convert the contents of the array to the parent:

List<Parent> parentList = childList.ConvertAll(x => (Parent)x);
TheChubbyPanda
  • 1,721
  • 2
  • 16
  • 37