C# generic function

  • Thread starter Thread starter Tao
  • Start date Start date
T

Tao

hi.. group

I have a question about generic fucntion. Let us say, I have a function
F<T>(int a);

can I do something like:

Type type = obj.GetType();
F<type>(3);

thanks.
 
Tao,

No, you can not. The type has to be known at compile-time in order to
make the call to the generic method like that.

What you can do is get the MethodInfo for the generic method, and then
call the MakeGenericMethod method on the MethodInfo instance. It will get
you a new MethodInfo instance which represents the method with the type
parameter that you pass in (you are going to pass in obj.GetType() in your
case).

Then, you can use reflection to make the clal on the MethodInfo
instance.

Hope this helps.
 
Tao,
Have you tried it? I bet you can get the answer yourself a lot faster than
waiting for replies to your post...
Peter
 
Back
Top