Are there any good resources out there that explain attributes and reflection and their many uses in depth?
I am especially interested in best practices, i.e. when it would be useful or appropriate to use attributes and reflection to solve specific computing problems.
I don’t know of a good comprehensive resource. In my experience, the best way to learn is to run into a situation that can’t be solved without it (at least not easily). So if you know the basic situations where reflection & attributes make things easier, you’ll know when you need to start learning them.
Reflection: appropriate when you can’t do what you need without it.
I know that sounds a little snarky, but it’s actually true – if you need to write some code but there is just no way to figure out the types of the objects you’re dealing with, reflection is appropriate. It’s also appropriate when you need to sneak in and use private/protected/internal members of an object you don’t control.
Attributes: appropriate when you need to add extra information about a type.
Example: I have a bunch of
IConverterclasses. Each one corresponds to a specific field in our content management system. How can I decorate this class with extra information which describes the field it is used for?It would be nice if I could just put some kind of extra piece of information on the class itself that says what field it’s for. Then I can check through all my types and find the one I want, and just instantiate that one. Attributes let me do that: