Reputation: 107072
Two questions about attributes:
The idea is that I want to make a list of all the classes in my assembly that have my attribute applied to it. I could of course iterate through all of them with reflection and check - but it would be nicer if the attribute could simply append to a global static list upon instantiation.
Upvotes: 7
Views: 1129
Reputation: 422320
Attributes are not automatically instantiated upon application startup. The only way to see which types (or any IL element, for that matter) has the attribute applied is to iterate everything and check one by one. Consequently, attributes can't automatically take control of a program.
They are basically metadata attached to some stuff. Their constructor is called when reflection instantiates the attribute class that represents the attribute at run time. This happens only when you request reflection to do so (by Type.GetCustomAttributes
method.)
Upvotes: 12