I came across some code the other day and I wondered if that was the best way to do it. We have a method that takes a string from some web form data a does something to an
The first case will almost always be faster. However, its performance comes from the fact that it can be early bound during compile time, but that is its biggest drawback as well: this approach cannot, for instance, handle dynamically loaded assemblies, and it is much more error-prone since it is imperative and not declarative. (Forgetting a newly implemented action for instance is a thing which could happen quickly.)
My usual approach is to use reflection to implement such patterns during discovery time, but to use delegates at invocation time. This gets you the flexibility of the reflection approach with performance very close to the early-bound approach.
Discovery phase: use reflection to find the members (using attributes, interfaces, signatures, and/or coding conventions). In your case you always have the same signature, so the delegate to use would be Action
. Add those members to a Dictionary
instance, creating a delegate from the MethodInfo
using CreateDelegate().
Invocation phase: get the delegate via its key and invoke it, which is very simple (here assuming the dictionary is called methods
): methods[action](o)