Why is the use of reflection in .NET recommended?

The main value of Reflection is that it can be used to inspect assemblies, types, and members. It’s a very powerful tool for determining the contents of an unknown assembly or object and can be used in a wide variety of cases.

Opponents of Reflection will cite that it is slow, which is true when compared to static code execution–however Reflection is used throughout the .NET framework, and provided that it’s not abused it can be a very powerful tool in the toolkit.

Some useful applications:

  • Determining dependencies of an assembly

  • Location types which conform to an interface, derive from a base / abstract class, and searching for members by attributes

  • (Smelly) testing – If you depend on a class which is untestable (ie it doesn’t allow you to easily build a fake) you can use Reflection to inject fake values within the class–it’s not pretty, and not recommended, but it can be a handy tool in a bind.

  • Debugging – dumping out a list of the loaded assemblies, their references, current methods, etc…

Leave a Comment