Posts about Reflection
It's always best to completely avoid using reflection, but unfortunately that's not always possible. Sometimes you need to use APIs, which are not strongly typed. In such cases you should transition from reflection to strongly typed code as soon as possible: because of performance, and because of code readability as well. In this blog post I'll describe a couple of techniques which are useful in situations like this.
Reflection is a great tool for calling methods on objects when their types are not known at compile time. Unfortunately the Type.GetMethod method doesn't work with generic methods, therefore we need to find the right method by iterating through all the methods returned by Type.GetMethods. Searching for alternatives I stumbled upon a solution using expression trees. It got me wondering though, which of the two solutions actually performs better.
It seems that no matter how much experience one has with .NET framework, there are still surprises awaiting him somewhere down the road. This time I'd like to point out an interesting behavior of MethodInfo.Invoke many of you might not be aware of. I certainly wasn't, until today.
Essentially everything you need to implement plugins in your application is some way to dynamically instantiate classes at runtime. In COM world this was achieved by calling the CreateObject function. In the managed world you should use AppDomain.CreateInstanceAndUnwrap.