Chapter 15. Attributes

 <  Day Day Up  >  

Declarations often have modifiers, such as Public or Overridable or ReadOnly , attached to them. These modifiers give the compiler and the .NET Framework extra information about the declaration, such as its accessibility, whether it can be overridden, and whether its value can be changed.

Modifiers have two problems, however. One is that modifiers have to be a part of the language ”that is, the compiler has to understand them specially, and they cannot be used in programs to name things (unless they are escaped, of course). This is a problem because the .NET Framework has many places where modifiers are desirable to change the Framework's runtime behavior, but it would be a large burden on the language to define new modifiers for all of them.

For example, the Framework can automatically synchronize access to a field by multiple threads. It would be desirable to have a modifier that could be applied to fields that would indicate that access should synchronized, but that would require adding a new keyword and new code to the compiler to understand it. Multiply this case by a hundred other kinds of Framework modifiers, and the language would quickly become unmanageable.

The other problem is that modifiers cannot be used to store programmer-defined information about the declarations in a program. For example, when defining a Windows control, a programmer might want to attach some information to the class that indicates to a development environment how to show the control in the toolbox. Or a programmer might want to attach some information to the classes in a class library so that an automated test tool could test the classes. But because modifiers are defined as part of the language and must be understood by the compiler, a programmer cannot add new modifiers.

These problems can be solved through the use of attributes . Attributes are classes that can be attached to declarations, just like modifiers. And like modifiers, the information stored in attributes is stored as part of the assembly and can be retrieved at runtime by the Framework or a program. Attributes allow the Framework to define new modifiers without requiring them to be defined in the Visual Basic .NET language, and they allow programmers to attach arbitrary information to their declarations.

 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

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