On 19 March 2012 08:46, dennis luehring <dl.soluz@gmx.net> wrote:

attributes does not containing code - there just a (at-runtime) queryable information that can be attached to serveral things (like classes, methods, ...) - think of it like double.epsilon - but extendable by users - thats it, and in the c# world these attribute-definitions tend to be something like an class (but without code)

in c# you can walk by (runtime)reflection through your code and find out if something is annotated with an special attribute and use the configure information and do something with it - call an constructor, open an connection, generated code (at runtime) - whatever you want

its a easy-to-use-buildin-attribution-system thats it - and people like them because c# do all the big magic by giving developers a bunch of attributes that are then used for stuff like serialization, memory-layout, ...

a compiletime example of this could be:

attribute my_special_attribute
{
  int version;
}

attribute my_special_attribute2
{
  string test;
}

class test
{
  [my_special_attribute(version=2)]
  int method1();

  [my_special_attribute(version=2)]
  [my_special_attribute2(test="bert")]
  int method2();
}

void main()
{
 auto b = [ __traits(allMembers, D) ];
 foreach( auto a; b )
 {
   -->attribute query magic
   -->auto c = [ __traits(attribute("my_special_attribute", a) ];
   -->auto c = [ __traits(attribute("my_special_attribute2", a) ];

   //now we know all methods with my_special_attribute
   //and speical_special_attribute2 and their content (version=2
   //and test="bert"

   //now think of an template or mixing that uses this
   //information for code-generation or something like that

   //thats all
 }
}

+1 this post