ASP.NET Hosting

Static method reflection

.NET reflection features are powerful and this is really what makes it a powerful platform. We don't use reflection everyday, but when we do it's really useful.
Don't you hate it though when you have to write code like this?:

MethodInfo method = typeof(MyClass).GetMethod("MyMethod");


The problem with this code is that we use a string to identify the method, which means that we don't get compile-time validation.
Ayende has an interesting approach to this problem. He gives you a solution that allows writing the following code instead:

MethodInfo method = GetMethod<int, string>(MyClass.MyMethod);

In this case, everything is strongly-typed and checked by the compiler.

Of course, nothing is perfect and this solution suffers from a number of limitations, but it's an interesting approach anyway. The limitations:
  • it works only with static methods,
  • the methods need to be accessible (public or in your code's reach),
  • we can't use a similar approach for properties.
Maybe one day we'll get support for this right from the compiler. Currently, there is typeof for types, but we are out of luck for methods, properties or parameters...

Update: Daniel Cazzulino has another option that is more complete.

5 Comments

Comments have been disabled for this content.