ECMA-334: 24.3.2 Run-time retrieval of an attribute instance


Jump to: navigation, search
C# Language Specification
© 2006 ECMA International

24.3.2 Run-time retrieval of an attribute instance

The attribute instance represented by T, C, P, and N, and associated with E can be retrieved at run-time from the assembly A using the following steps:

  • Follow the run-time processing steps for executing an object-creation-expression of the form new T(P), using the instance constructor C and values as determined at compile-time. These steps either result in an exception, or produce an instance of T. Call this instance O.
  • For each named-argument Arg in N, in order:
    • Let Name be the identifier of the named-argument Arg. If Name does not identify a non-static public read-write field or property on O, then an exception is thrown.
    • Let Value be the result of evaluating the attribute-argument-expression of Arg.
    • If Name identifies a field on O, then set this field to the value Value.
    • Otherwise, Name identifies a property on O. Set this property to the value Value.
    • The result is O, an instance of the attribute class T that has been initialized with the positional-argument-list P and the named-argument-list N.

[Note: The format for storing T, C, P, N (and associating it with E) in A and the mechanism to specify E and retrieve T, C, P, N from A (and hence how an attribute instance is obtained at runtime) is beyond the scope of this standard. end note]

[Example: In an implementation of the CLI, the Help attribute instances in the assembly created by compiling the example program in §24.1.2 can be retrieved with the following program:

using System;
using System.Reflection;
public sealed class InterrogateHelpUrls
{
   public static void Main(string[] args) {
      Type helpType = typeof(HelpAttribute);
      string assemblyName = args[0];
      foreach (Type t in Assembly.Load(assemblyName).GetTypes()) {
         Console.WriteLine("Type : {0}", t.ToString());
         HelpAttribute[] helpers =
            (HelpAttribute[])t.GetCustomAttributes(helpType, false);
         for (int at = 0; at != helpers.Length; at++) {
            Console.WriteLine("\tUrl : {0}", helpers[at].Url);
         }
      }
   }
}

end example]



Personal tools