Geeks With Blogs
New Things I Learned
Every now and then I have a need to call a generic method, but I can't quite call it generically.  Usually that particular situation involves needing to call a generic method, and I have the type for that generic method.  There are various reasons/examples of why anyone would get to this point, in my case we have an infrastructure code that can deal with objects generically, but  because it is infrastructure code, we can't have it refer to the actual entity classes that are in the higher layer/tier.

However, if we only have the type, we can't just call the method as is, we have to call it via reflection.  And as much as I like reflection, it has some drawbacks.  Consider the following snippet:

public void InvokeGenericMethod(object o)

{

   MethodInfo mi = this.GetType().GetMethod("MyGenericTestMethod", BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance);

   mi = mi.MakeGenericMethod(new Type[] { o.GetType() });

   mi.Invoke(this, new object[] { o });

}
 

private string MyGenericTestMethod<T>(T value)

{

   return value.GetType().ToString();

}

To call the method (it is private), I have to call Type.GetMethod with some not very nice looking parameters.  The name supplied is in quotes; as such if the actual method name is changed, this code will still compile, it'll just crash when actually ran.  Mind you, the code works; it's just not very maintenance-friendly.

A trick I use for this then is to use delegates as follows:

public void InvokeGenericMethod(object o)

{

   Func<string, string> temp = MyGenericTestMethod<string>;

   MethodInfo mi = temp.Method.GetGenericMethodDefinition();

   mi = mi.MakeGenericMethod(new Type[] { o.GetType() });

   mi.Invoke(this, new object[] { o });

}
 

private string MyGenericTestMethod<T>(T value)

{

   return value.GetType().ToString();

}

By using delegates, I no longer need to use reflections to get the method to call; I just point to the method as a delegate, and then create a generic method definition from that delegate.  Everything after that is still the same.  One nice benefit to this is if the method name is changed, the refactoring engine will also change the delegate reference, and if it doesn't the code will fail at compile-time.  Nicer, cleaner looking code as well, IMHO. Posted on Friday, August 22, 2008 9:41 AM .NET | Back to top


Comments on this post: Calling Generic Method when given a type

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Muljadi Budiman | Powered by: GeeksWithBlogs.net