How can I cast an object
to IEnumerable
?
I know that the object implements IEnumerable
but I don\'t kn
It's hard to answer this without a concrete use-case, but you may find it sufficient to simply cast to the non-generic IEnumerable
interface.
There are two reasons why this will normally work for most types that are considered "sequences".
IEnumerable
.IEnumerable
interface inherits from IEnumerable
, so the cast should work fine for the generic collection classes in System.Collections.Generic, LINQ sequences etc.EDIT:
As for why your provided sample doesn't work:
IEnumerable
as an IEnumerable
.IEnumerable
is covariant, since variance is not supported for value-types - the cast from int[]
(an IEnumerable
) --> IEnumerable
can't succeed.