Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use reflection? Patterns/anti-patterns

Tags:

c#

reflection

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?

like image 288
StackUnderflow Avatar asked Jan 09 '09 22:01

StackUnderflow


3 Answers

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.

like image 192
ctacke Avatar answered Oct 18 '22 02:10

ctacke


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.

like image 20
Harper Shelby Avatar answered Oct 18 '22 02:10

Harper Shelby


I don't know if it is a pattern but I use reflection to generate SQL from DAO's class definitions.

like image 11
Otávio Décio Avatar answered Oct 18 '22 02:10

Otávio Décio