Solution to "Unable to cast object of type '[type1]' to type '[type2]'." when trying to cast a List to List

Okay, it’s not really a “solution” per se, but more of a workaround to a limitation with generic List objects that has to do with covariance and contravariance.

I struggled with this for way too long, hope you save you some time.

I have a list that contains a Heavy object that I don’t want to serialize down to the client. So I created a Slim version of it with an explicit operator to convert from Heavy to Slim.

public class WorkItem
{
public int Id { get; set; }
}
public class WorkItemSlim
{
public int Id { get; set; }
public static explicit operator WorkItemSlim(WorkItem workItem)
{
var wis = new WorkItemSlim();
wis.Id = workItem.Id;
return wis;
}
}

This works great when explicitly casting a single Heavy object to a Slim object like so:

var workItem = new WorkItem();
workItem.Id = 1;
WorkItemSlim wis = (WorkItemSlim)workItem;

But you get “Unable to cast object of type ‘[type1]’ to type ‘[type2]’.” when you try to cast a List<WorkItem> to List<WorkItemSlim>

I spent a lot of timing looking at my explicit operator trying to figure out what I did wrong, but after some searching I discovered that a List<T> isn’t supported at runtime.

So the (not so great) solution is to convert each object of the list (one by one) to the other type.

var workItemSlimList2 = workItemList.ConvertAll(m =&gt; (WorkItemSlim)m);

I hope I saved you some time.

Jon