C# – Unable to cast an object of type “object {System.Collections.Generic.List}” as ICollection

cnet

Why can you not cast a object which at runtime has type object {System.Collections.Generic.List<string[]>} as an ICollection<object>?

I'm sure its something obvious but I cant figure it out.

It gives the exception –

Unable to cast object of type
'System.Collections.Generic.List1[System.String[]]' to type
'System.Collections.Generic.ICollection
1[System.Object]'.

Best Answer

Before C# 4.0, generics are not covariant. If you are not using C# 4.0, you can accomplish this cast like this:

List<string[]> list = new List<string[]>();
//...Fill the list...
ICollection<object> collection = list.ConvertAll<object>(item => item as object);