Attributes Overview

If you have used C++, you are probably familiar with declarations that contain keywords, such as public and private, that provide additional information about class members. These keywords further define the behavior of class members by describing their accessibility to other classes. Because compilers are explicitly designed to recognize predefined keywords, you do not traditionally have the opportunity to create your own. The common language runtime, however, allows you to add keyword-like descriptive declarations, called attributes, to annotate programming elements such as types, fields, methods, and properties.

When you compile your code for the runtime, it is converted into Microsoft intermediate language (MSIL) and placed inside a portable executable (PE) file along with metadata generated by the compiler. Attributes allow you to place extra descriptive information into metadata that can be extracted using runtime reflection services. The compiler creates attributes when you declare instances of special classes that derive from System.Attribute.

The .NET Framework uses attributes for a variety of reasons and to address a number of issues. Attributes describe how to serialize data, specify characteristics that are used to enforce security, and limit optimizations by the just-in-time (JIT) compiler so the code remains easy to debug. Attributes can also record the name of a file or the author of code, or control the visibility of controls and members during forms development.

You can use attributes to describe your code in practically any way conceivable and to affect run-time behavior in creative new ways. Attributes allow you to add your own descriptive elements to C#, Visual C++, Microsoft Visual Basic 2005, or any other language that targets the runtime, without having to rewrite your compiler.

See Also



Other Resources

Extending Metadata Using Attributes