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
}

2 Answers

2
Adrian On Best Solutions

Use Enumerable.Cast<T>:

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

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

List<Parent> parentList = childList.ConvertAll(x => (Parent)x);