Attributes

I l @ ve RuBoard

New to .NET is the concept of attributes. Attributes are declarative tags that can be applied to various members and methods . That information can then be viewed using the System.Reflection API. The details of reflection are beyond the scope of discussion for our purposes, but the importance of attributes necessitates a brief tour. Listing 2.2.5 demonstrates the use of the Conditional attribute provided by the .NET framework classes.

Listing 2.2.5 The Conditional Attribute
 1: //File        :part02_36.cs  2: //Author    :Richard L. weeks  3: //Purpose    :The Conditional attribute  4: //  5: //Compile instructions:  6: // csc /define:DEBUG part02_36.cs  7: // csc part02_36.cs  8:  9: using System; 10: using System.Diagnostics;    //The ConditionalAttribute lives here 11: 12: public class Foo { 13: 14:     [Conditional("DEBUG")] 15:     public void OnlyWhenDebugIsDefined( ) { 16:         Console.WriteLine("DEBUG is defined"); 17:     } 18: } 19: 20: public class AttributeTest { 21:     public static void Main( ) { 22:         Foo f = new Foo( ); 23:         f.OnlyWhenDebugIsDefined( ); 24:     } 25: } 

The best way to get a quick understanding of attributes is to look at one up close. Listing 2.2.5 makes use of the Conditional attribute. As the name implies, the Conditional attribute is used during conditional compilation. Take a look at line 14. The Conditional attribute is applied to the OnlyWhenDebugIsDefined method. In essence, the OnlyWhenDebugIsDefined will only be available when DEBUG is defined during the compilation process. Notice that line 23 makes a call to the OnlyWhenDebugIsDefined method and yet does not have any conditional markers. This is an added benefit of the Conditional attribute. There is no need to wrap code up in conditional #ifdef types of preprocessor statements.

As a point of interest, methods marked with the Conditional attribute are still included in the compiled assembly. However, all calls to the method are removed. In a final release build, all conditional code should be excluded from the compilation process by making use of #if style preprocessor statements.

.NET makes use of attributes not only for conditional compilation, but also for WebServices, XML, and Windows Services, just to name a few. Attributes are not limited to C#; they can also be found in ATL Server, the next generation of ATL from Microsoft.

Like all aspects of the .NET framework, the ability to create custom attributes exists. All attributes inherit from the System.Attribute base class. Creating and using custom attributes could easily fill a small book, so its exploration is left to you.

I l @ ve RuBoard


C# and the .NET Framework. The C++ Perspective
C# and the .NET Framework
ISBN: 067232153X
EAN: 2147483647
Year: 2001
Pages: 204

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