1

I have a Type variable t passed into a method, and I want to use it as a generic parameter when calling IQueryable.Join like the following

queryResult.Join<Type1, Type2, t, Type3>( items, outerSelector, innerSelector, ( a, b) => a);

It obviously doesn't work. What should I do to t in order to achieve what I intended? Thanks!

uni
  • 613
  • 1
  • 7
  • 11

2 Answers2

5

Basically you've got to call the method with reflection:

  • Get the generic method template with Type.GetMethod
  • Call MakeGenericMethod passing in your 4 type parameters
  • Invoke the method passing in the regular arguments

It's a pain :(

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

I'm not sure of the details of your "type variable," but if the variable is already a generic parameter to the method, you can use it as a generic parameter to Join also:

public void MyMethod<T>()
{
    // do some stuff to get queryResult, then
    queryResult.Join<Type1, Type2, T, Type3>(items, outerSelector, innerSelector, (a, b) => something);
}
Andrew
  • 14,325
  • 4
  • 43
  • 64
  • I see I've been Skeeted here, but I'll point out too that, in my example, T must be determinable at compile time. Carry on. – Andrew Oct 13 '11 at 21:54
  • Thanks, Andrew. In this case, T can't be determined at compile time.. :( – uni Oct 13 '11 at 21:57
  • 1
    Are you sure? Well, OK, yes, you're sure, but sometimes there is a way to refactor so that T is determinable at compile time. What are you trying to accomplish? – Andrew Oct 13 '11 at 22:04
  • Absolutely, that's always nicer.. The thing is that I tried to refactor this monster this whole day without any luck, so I think I need to fall back.. – uni Oct 13 '11 at 23:23