Dan
Dan

Reputation: 13343

When are Attribute Objects created?

Since Attributes are really just Metadata attached to assemblies, does that mean that Attribute Objects are only created on request (such as when you call GetCustomAttributes)?

Or are they created on creation of the object?

Or, a combination of the first 2, created when the object is created due to attribute scanning by the CLR?

Upvotes: 13

Views: 804

Answers (3)

Hans Passant
Hans Passant

Reputation: 941397

It is not quite that clean, attributes also affect code generation. Some attributes are interpreted by the compiler, [DllImport] for example. Some are discovered by the jitter, [MethodImpl] for example. This is infinitely extended to other tools and classes in the framework that were written to take advantage of attributes.

But these tools are just doing what you need to do if you want to find your own attributes, calling GetCustomAttributes() is required. That kind of code is never associated with an instance of the object, attributes apply to types.

Upvotes: 2

to StackOverflow
to StackOverflow

Reputation: 124696

They are created on request.

For example, if you add some .NET 3.0 attributes to a .NET 2.0 Assembly (e.g. WCF DataContractAttribute), you'll still be able to use the .NET 2.0 Assembly on a machine that doesn't have .NET 3.0 installed, provided you don't have any code that attempts to access the attributes.

Upvotes: 4

Smi
Smi

Reputation: 14326

From CLR via C#, third edition:

If you want to construct an attribute object, you must call either GetCustomAttributes or GetCustomAttribute. Every time one of these methods is called, it constructs new instances of the specified attribute type and sets each of the instance’s fields and properties based on the values specified in the source code. These methods return references to fully constructed instances of the applied attribute classes.

So yes, they are only created on request.

Upvotes: 9

Related Questions