Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: When are attributes instantiated and can I get a reference to the type they are decorating?

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.

like image 355
Vilx- Avatar asked Aug 20 '09 12:08

Vilx-


People also ask

How can you specify target for custom attribute?

Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.

How would you define a custom attribute that can only be applied to class code elements?

The following code fragment specifies that a custom attribute can be applied to any class or method: C# Copy. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] End Class.

How does attributes work in C#?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.


1 Answers

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

like image 118
mmx Avatar answered Oct 13 '22 07:10

mmx