Applying Attributes to Code


Attributes are classes that expand the information about other programming elements. You can apply attributes to various elements including: the assembly, classes, members , parameters, etc. Microsoft has defined a number of attributes that control how the compiler works and how the runtime works. You can also define your own attributes, as you will see later.

To apply attributes to code elements.

  1. In front of the element, type an open square bracket [ .

  2. If the attribute is for the assembly ( project level) type assembly : otherwise continue to step 3.

  3. Type the name of the attribute without the attribute suffix. Attribute classes are named "SomethingAttribute" but when applying the attribute you can omit the Attribute suffix and just use the word "Something." For example, ColorAttribute would be applied as: [Color... .

  4. Type an open parenthesis ( .

  5. Type any parameters for the constructor of the attribute class separated by commas. Parameters vary depending on the attribute. To know what parameters to set you have to look it up in the documentation.

  6. You can also set the attributes of any public field in the class, type fieldname = value , where fieldname is the name of a public field in the class. Check documentation for the names of public fields.

  7. Type a close parenthesis ) .

  8. Type a close square bracket ] ( Figure 12.26 ).

    Figure 12.26 Serializable and NonSerialized are attributes provided by Microsoft. They tell certain classes in the framework (conveniently known as serializers) that the contents of your class can be persisted either to memory, or to the drive. NonSerialized tells the class not to persist the contents of a field.
      [Serializable()]  class Address {    public string Street;    public string City;    public string ZipCode;  [NonSerialized]  public string SecurityCode; } 

graphics/tick.gif Tip

  • You can combine more than one attribute per element by separating the attributes with commas ( Figure 12.27 ).

    Figure 12.27 You can combine multiple attributes by separating them with commas.
      [VisibleColumn(false),ColumnWidth(200)]  public string ID {    get    {       return _id;    }    set    {       _id = value;    } } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net