4

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

ilias
  • 2,620
  • 2
  • 27
  • 37
  • What do you mean, you don’t have the type at compile time? What else would `T` be in your example in `IEnumerable` (second line)? – Konrad Rudolph Mar 31 '10 at 13:53
  • If you don't know the type at compile-time then you wouldn't be able to use `typeof` either. You should update your example code. – LukeH Mar 31 '10 at 14:05
  • Updated the example code to make things more clear. – ilias Mar 31 '10 at 14:30
  • unfortunately, your clarification doesn’t really help. You *still* need to know the type `T` at compile time. – Konrad Rudolph Mar 31 '10 at 15:38
  • possible duplicate of [Dynamically Create a generic type for template](http://stackoverflow.com/questions/67370/dynamically-create-a-generic-type-for-template) – nawfal Jan 17 '14 at 15:04

1 Answers1

4

You can use reflection to call Cast<> with a runtime type. See this answer: 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.

Community
  • 1
  • 1
Alex J
  • 9,905
  • 6
  • 36
  • 46