CSharpFeeds - All your C# feeds in one place.

Sponsors

Wednesday, July 05, 2006

Static method reflection

by fmarguerie via Fabrice's weblog on 7/5/2006 4:06:00 PM

.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.
Share this post: Email it! | bookmark it! | digg it! | reddit!
email it!bookmark it!digg it!

Original Post: Static method reflection

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us