0

Possible Duplicate:
Calling generic method with a type argument known only at execution time

I have a generic method and I want it to call it with a already known Type-Object in Runtime.

public class someClass {
  public void someGenericMethod<T>()
  {
     //some Code to Execute
  }

  public void someMthod()
  {
     Type objectType = someInstance.getType();

     someGenericMethod<objectType>(); //this isn't valid code, but I want to do something like this.
  }
}

Is there a way to do this in C#/.net or is there a workaround?

Community
  • 1
  • 1
Stelzi79
  • 585
  • 3
  • 12
  • What are you trying to accomplish? There's much to be left to the imagination in `someGenericMethod`. Do you need that method to be generic? Can you instead pass a type as a parameter? – George Johnston Nov 28 '11 at 21:25
  • 3
    @George, IMO, there is only one logical way to interpret what the OP intended with his example. – Kirk Woll Nov 28 '11 at 21:26
  • sorry for the duplicate. (Haven't found this question with my search terms) – Stelzi79 Nov 28 '11 at 21:34

2 Answers2

3

It's possible, but it's ugly:

var method = typeof (someClass).GetMethod("someGenericMethod").MakeGenericMethod(objectType);
method.Invoke(this, null);
Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
  • I can't imagine this being to performance friendly either, correct? – Matthew Cox Nov 28 '11 at 21:26
  • @Matthew, the initial Reflection call to find the method is pretty slow, but the dynamic Invoke shouldn't be too bad (speaking anecdotally; haven't actually quantified these estimates.) You can speed up the Invoke portion (if you need to Invoke frequently) by using Delegate.CreateDelegate (not too hard in this case, as the type parameter is not used for the return value or any parameters.) If the type parameter is used, that creates further complications (which you can work around if you really want to with DynamicMethod and Emit.) – Dan Bryant Nov 28 '11 at 21:31
3

You can use reflection:

var genericMethod = typeof(someClass).GetMethod("someGenericMethod");
var methodInstance = genericMethod.MakeGenericMethod(objectType);
methodInstance.Invoke(someInstance, null);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523