Rex Jaeschke is an independent consultant, author, and seminar leader. He serves as editor of the standards for C++/CLI, CLI, and C#. Rex can be reached at http://www.RexJaeschke.com.
The runtime environment permits keyword-like descriptive declarations, called attributes, to be present on program elements such as types, fields, functions, and properties. Attribute information is stored in the metadata output by a compiler. As such, it can be used to describe the code to the runtime, or to modify somehow behavior at run time.
In this article, we'll see some of the attributes provided by the .NET Framework, and we'll look at several in detail.
Introduction
Depending on how it was defined, an attribute can be applied to one or more program elements. The general form of an attribute is as follows:
[assembly:Attrib1( ... )] [Attrib2( ... )] public ref class C { [Attrib3( ... )] member declaration }
In C++/CLI, an attribute is specified inside a pair of matching brackets ([]), as shown above. An attribute can be attached to the assembly as a whole (as with Attrib1), to a type (as with Attrib2), or to a member of a type (as with Attrib3). It can even be attached to a particular parameter in a function declaration, or to the return type of a function (neither of which is shown here).
In previous installments, we saw the use of a number of attributes provided by the .NET Framework; they are: Flags, ThreadStatic, Serializable, and NonSerialized.
The full name of an attribute class contains the suffix Attribute; for example, the full name of the attribute ThreadStatic is really ThreadStaticAttribute; however, the suffix can be omitted, and it has been throughout this text.
When an attribute is used, a call to its constructor is placed within the brackets. To see what arguments can be passed to that constructor, consult the on-line help for the given attribute. Apart from having one or more fixed arguments, some arguments can be passed by name rather than by position. For example,
[DllImport("MyLib.DLL", EntryPoint = "MyFunction", SetLastError = true, CharSet = CharSet::Unicode, ExactSpelling = true, CallingConvention = CallingConvention::StdCall)]
In such cases, the ordering of the named arguments is irrelevant.