3

I can create a cast function generically like this:

public IEnumerable<T> Convert<IEnumerable<T>>(object input) {
    return (IEnumerable<T>) input; // this works
}

But say, I don't have T, but I have Type. How do I get this to work?:

// object is a List<int>, Type is typeof(int)
public object Convert(object input, Type type) {
    return IEnumerable<Type> input; // this does not work
}
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • Casting is a compile-time operation; reflection is for run-time analysis. It's really not clear what you're trying to do or why. Can you explain more? – Eric Lippert Nov 23 '18 at 02:48
  • ok, i see - i wonder if adding the word `enum` into the title might be of use? eg `How to cast to a generic enum type using reflection?` – jazb Nov 23 '18 at 02:49
  • "object is a List, Type is typeof(int)" ??? What exactly do you expect to happen in converting a List to an int other than an error? – TnTinMn Nov 23 '18 at 04:12
  • Well, if implemented correctly, I expect it not to error:). Sorry, I'm trying to write pseudo code here – Michael Kang Nov 23 '18 at 04:14

0 Answers0