J.W.
J.W.

Reputation: 18181

Is .Net attribute feature used at compile-time or run-time or both?

In .Net, is the attribute feature used at compile-time or run-time or both? Can you give me some examples?

Upvotes: 13

Views: 4018

Answers (4)

Daniel Brückner
Daniel Brückner

Reputation: 59705

Attributes are output as metadata to the assembly at compile time. This meta data is then used at runtime via reflection - for example using GetCustomAttributes().

Some attributes are used by the compiler at compile time, too. For example the compiler looks at the AttributeUsageAttribute to determine if an attribute can be used for a specific object.

Upvotes: 10

Marc Gravell
Marc Gravell

Reputation: 1064324

Most are used at runtime only. A very limited number are used by the compiler, including:

  • [Conditional(...)] - omit method calls per build symbols
  • [Obsolete(...)] - emit a warning/error as build output
  • [Serializable] - gets written as a CLI flag
  • [Extension] - used for extension methods
  • [AttributeUsage] - affects how attributes are applied
  • -

There are a range of things like [AssemblyVersion], [AssemblyFileVersion] etc that are used by the compiler when creating the assembly file, and things like [InternalsVisibleTo] which affect accessibility.

Additionally, tools like PostSharp do extra post-compile steps based on attributes.

There are some other attributes that the compiler may add to generated types/methods (for anon-methods / types, iterator blocks, etc).

Upvotes: 16

Michael Bray
Michael Bray

Reputation: 15285

The compiler adds what is called metadata to the object that is decorated with an attribute. This metadata, whether created via attributes or otherwise, is all accessible at run-time thru Reflection. Thus, you can decorate with attributes and then read the details when the program is running. However, to say that the metadata is "used" at compile time isn't quite correct, as the compiler doesn't care what metadata there is.

Upvotes: 0

ConsultUtah
ConsultUtah

Reputation: 6829

Attributes are compiled into the code at compile time, but they are often used at runtime as triggers to do things differently.

Upvotes: 1

Related Questions