Custom attributes C#

Ary Manzana ary at esperanto.org.ar
Thu Sep 27 08:00:16 PDT 2007


They allow you to add information about classes, methods, etc, directly 
in their source code. Then you can access that information either at 
compile time or runtime. So for example you can have a class that 
represents an object that maps to a database:

[Table("Person")]
class Person {

   [PrimaryKey("Id")]
   int id;

   [Field("Name")]
   char[] name;

}

Then you can have a class that knows how to save objects into a database 
by just querying those attributes. This is very comfortable since you 
have the specification of how to map a class to a database right in the 
class' definition, instead of in another file.

I guess they are a generalization of attributes like "public", "static", 
"const", etc (you could have [Public], but it's more verbose).

An example of a compile-time attribute is [SuppressWarning(id)] (in 
Java, at least), that instructs the compiler to not generate some 
warnings for a certain class, method, etc.

Janice Caron wrote:
> This is obviously some strange usage of the word "explain" that I
> wasn't previously aware of :-(
> 
> Any chance anyone could explain what that means? Square brackets mean
> array access to me, so just sticking function calls in square brackets
> where it would be a syntax error to do so does not really constitute
> an explanation in my book.



More information about the Digitalmars-d mailing list