When do you use reflection? Patterns/anti-patterns

I understand the reflection API (in c#) but I am not sure in what situation would I use it. What are some patterns - anti-patterns for using reflection?


Solution 1:

In one product I'm working on we use it a lot, but Reflection is a complex, slow beast. Don't go looking for places to use it just because it sounds fun or interesting. You'll use it when you run into a problem that can't be solved in any other way (dynamically loading assemblies for plug ins or frameworks, assembly inspection, factories where types aren't know at build, etc). It's certainly worth looking at reflection tutorials to see how it works, but don't fall into the trap of "having a hammer and everything looking like a nail." It's got very specialized use cases.

Solution 2:

The only place I've used the Reflection stuff in C# was in factory patterns, where I'm creating objects (in my case, network listeners) based on configuration file information. The configuration file supplied the location of the assemblies, the name of the types within them, and any additional arguments needed. The factory picked this stuff up and created the listeners based on that.