Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast received object to a List<object> or IEnumerable<object>

Tags:

c#

.net

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        }       else       {           ... 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.

like image 404
Sergio Romero Avatar asked Mar 10 '09 22:03

Sergio Romero


People also ask

Can object be cast to list?

you can always cast any object to any type by up-casting it to Object first. in your case: (List<Customer>)(Object)list; you must be sure that at runtime the list contains nothing but Customer objects.

How do I cast an object to a type in C#?

We cast a value by placing the targeted type in parentheses () next to the value we want to cast. C#'s compiler allows many different kinds of casting. For example, we can cast an int to a double , a char to an int , or a float to a decimal .

What is IEnumerable string in c#?

IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.


1 Answers

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

IList collection = (IList)myObject; 
like image 134
erikkallen Avatar answered Sep 22 '22 05:09

erikkallen