tags:

views:

160

answers:

1

Hi,

I get an IEnumerable which I know is a object array. I also know the datatype of the elements. Now I need to cast this to an IEnumerable<T>, where T is a supplied type. For instance

IEnumerable results = GetUsers();
Type t = GetType(); //Say this returns User
IEnumerable<T> users = ConvertToTypedIEnumerable(results, t);

I now want to cast/ convert this to IEnumerable<User>. Also, I want to be able to do this for any type.

I cannot use IEnumerable.Cast<>, because for that I have to know the type to cast it to at compile time, which I don't have. I get the type and the IEnumerable at runtime.

- Thanks

+4  A: 

You can use reflection to call Cast<> with a runtime type. See this answer: http://stackoverflow.com/questions/1941263/how-to-call-a-generic-method-through-reflection

However, at some point you'll still have to know the type of the item at compile time if you ever want to manipulate it as such without reflection. Just having an IEnumerable<T> instance cast as an object/IEnumerable still won't really do you any more good than just having the IEnumerable by itself. It's likely that you need to rethink what you're doing.

Ilia Jerebtsov