Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 382
J.W. Avatar asked Feb 22 '10 15:02

J.W.


2 Answers

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.

like image 75
Daniel Brückner Avatar answered Sep 17 '22 13:09

Daniel Brückner


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

like image 45
Marc Gravell Avatar answered Sep 19 '22 13:09

Marc Gravell