.NET: When are attributes created, and can I get a reference to the type that they adorn?

Two questions about attributes:

  • When are attribute classes created? When does a type first open or is at the start of execution?
  • Inside the attribute class, can I find out what type the attribute instance was created for?

The idea is that I want to make a list of all the classes in my assembly to which my attribute applies. I could, of course, iterate over all of them with reflection and validation - but it would be better if the attribute could simply join the global static list when creating the instance.

+6
attributes
source share
1 answer

Attributes are not automatically created when the application starts. The only way to see which types (or any element of the IL, for that matter) has the attribute used is to iterate over everything and check one by one. Therefore, attributes cannot automatically control the program.

This is mainly metadata related to some things. Their constructor is called when reflection creates an instance of the attribute class that represents the attribute at run time. This only happens when you request a reflection for this (using the Type.GetCustomAttributes method.)

+11
source share

All Articles