views:

187

answers:

1

Two questions about attributes:

  1. When are attribute classes instantiated? When the type is first accessed, or at the start of execution?
  2. From within the attribute class, can I find out for which type the attribute was instantiated?

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.

+9  A: 

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.)

Mehrdad Afshari
A pity. OK.
Vilx-