Information Technology Reference
In-Depth Information
Using Reserved Attributes
There are several attributes reserved by .NET that are designed to be processed by the com-
piler. You've already seen AttributeUsage , but there are two others you should know about—
the Obsolete and Conditional attributes.
The Obsolete Attribute
You saw the Obsolete attribute in the first example in this chapter. It allows you to mark a pro-
gram construct as obsolete and to display a helpful warning message when the code is compiled.
There is another overload of the constructor for Obsolete that takes a second parameter, of
type bool . This parameter specifies whether use of the target should be flagged as an error or as
a warning. The following code specifies that it should be flagged as an error.
Flag as an error.
[ Obsolete("Use method SuperPrintOut", true) ] // Apply attribute to method.
static void PrintOut(string str)
{ ...
The Conditional Attribute
The Conditional attribute allows you to either include or exclude all the invocations of a par-
ticular method. To use the Conditional attribute, apply it to the method declaration, along
with a compilation symbol as a parameter.
￿
If the compilation symbol is defined, the compiler will include the code for all the invo-
cations of the method, the way it would for any normal method.
￿
If the compilation symbol is not defined, the compiler will omit all the method invoca-
tions, throughout the code.
The CIL code for the method itself is always included in the assembly. It is just the invoca-
tions that are included or omitted.
For example, in the following code, the Conditional attribute is applied to the declaration
of a method called TraceMessage . The attribute has a single parameter, which is the string
DoTrace . When the compiler is compiling the code, it will check whether there is a compilation
symbol named DoTrace defined.
￿ f DoTrace is defined, the compiler will include all the calls to method TraceMessage ,
as usual.
If there is no DoTrace compilation symbol defined, it will not output code for any of the
calls to TraceMessage .
￿
Search WWH ::




Custom Search