3

I have a generic method, with the following signature

 private static void ProcessItem<T>(int id) where T : BaseItem

And it gets called in the following way

ProcessItem<RedItem>(id: 2)
ProcessItem<BlueItem>(id: 7)

My issue is that I get the type of item on application start up via reflection as a Type object. So now I am looking for a way that I can construct an expression tree that will result in a lambda that calls this method with the appropriate type.

So I can do something like lambda.Invoke(Type type, int id). And this will call something along the lines of id => ProcessItem<type>(id)

I found a similliar issue answered here: https://stackoverflow.com/a/2850366/5493420

However, the answer there shows how to instantiate a generic param of IEnumerable<> whereas I simply need to call my method, transforming the Type object into an actual <Type> parameter that my method can accept.

I am not exactly sure if this is even possible (converting a Type object into an actual type parameter), but would love to hear any suggestions on the topic.

PS: I am also willing to take a different approach (some reflection tricks maybe), as long as it doesn't affect performance by more than 10-20%

Kobek
  • 1,149
  • 6
  • 18
  • 40
  • 1
    There is no way to write *efficient* expression which receives `Type` argument (the body has nit use reflection, which would make if worst than using reflection directly). Reflection or cached delegates (in some dictionary by `Type`) are the only options I see. – Ivan Stoev Jan 08 '18 at 12:28
  • Thanks for the quick reply, can you expand on your idea for cached delgates. Do you mean that I have a predefined delagte with the correct type for each type object? Cause this will defeat the whole purpose of me doing this dynamically – Kobek Jan 08 '18 at 12:39
  • Something like static `Dictionary>` which you populate on demand for each `T`. – Ivan Stoev Jan 08 '18 at 12:43
  • 1
    I think this answer is what you need: https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method – Emerson Cardoso Jan 08 '18 at 12:52
  • Yeah, I just tried this. Worked like magic. Weird how I did not find it before. Anyways, thank you and @nvoigt, who reported it as duplicate for helping me find it – Kobek Jan 08 '18 at 12:57

0 Answers0