Improved type safety when dealing with generic types, generic methods and reflection

Compile-time safety is always important, as it reduces the chances that a refactoring can break existing code that compiles successfully. This benefit took me previously to the path of using expression trees to achieve strong-typed reflection.

There is, however, an alternative that works on previous versions of .NET and doesn’t involve expression trees. It essentially involves creating a delegate of the target method, and using the delegate properties to get to the corresponding MethodInfo:

Action<string> writeLine = Console.WriteLine;
MethodInfo writeLineMethod = writeLine.Method;

Note that the code above is very explicit about which overload of the WriteLine method to pick: the one with a single string argument and a void return value. You can leverage Action and Func various overloads to represent pretty much any method invocation. Also, if those do not fit, you can still create your own delegate type. The benefit, clearly, is that you now can refactor the defining class or method and the change will be picked automatically....

Read full article

No Comments