Cast received object to a List or IEnumerable


I'm trying to perform the following cast

private void MyMethod(object myObject)  
    if(myObject is IEnumerable)  
        List<object> collection = (List<object>)myObject;  
        ... do something   
        ... do something  

But I always end up with the following excepction:

Unable to cast object of type 'System.Collections.Generic.List1[MySpecificType]' to type 'System.Collections.Generic.List1[System.Object]'

I really need this to work because this method needs to be very generic to receive single objects and collections both of unspecified types.

Is this possible, or is there another way of accomplishing this.

Thank you.

3/10/2009 10:47:28 PM

Accepted Answer

C# 4 will have covariant and contravariant template parameters, but until then you have to do something nongeneric like

IList collection = (IList)myObject;
3/10/2009 10:51:18 PM

You can't cast an IEnumerable<T> to a List<T>.

But you can accomplish this using LINQ:

var result = ((IEnumerable)myObject).Cast<object>().ToList();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow