Jason Quinn
Jason Quinn

Reputation: 2573

Unable to cast an object of type "object {System.Collections.Generic.List<string[]>}" as ICollection<object>

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.ICollection1[System.Object]'.

Upvotes: 1

Views: 21203

Answers (2)

FishBasketGordo
FishBasketGordo

Reputation: 23142

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);

Upvotes: 4

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

See Variance in Generic Interfaces

Upvotes: 2

Related Questions