Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Get Personal with C# Custom Attributes : Page 4

C# attributes may seem like an insignificant element of C# grammar, but did you know they provide a powerful way to extend your metadata? This goes a long way towards simplifying component-based programming. Here's what you need to know about custom attributesand how to use them.


advertisement
Compile Time Attributes
These attributes regroup attributes that participate in the compilation. There are two categories of compile time attributes: attributes that generate errors or warnings and attributes that change the compiled code in some way. This section examines two compile time attributes supported by C# out of the box: Obsolete and Conditional.

Obsolete
This attribute is used to indicate that a type or member should not be used anymore. The compiler then yields a message each time it detects a member or type marked as obsolete.

void Test () { SomeOldMethod(); } [Obsolete("Use something else", /*IsError*/ false)] void SomeOldMethod() {}

Compile the preceding code and you should see the following warning:


c:\...: warning CS0618: '...SomeOldMethod()' is obsolete: 'Use something else'

This kind of message is helpful for code maintenance, plus the attribute gives you a nice way to extend the language without polluting the grammar with unnecessary "obsolete" keywords.

Conditional
This attribute tells the C# compiler that method calls should be discarded unless you apply a specified preprocessing identifier to the calling entity.

void Test () { WriteSomeDebugInfo(); } [System.Diagnostics.Conditional("DEBUG")] void WriteSomeDebugInfo() { //... do something here }

In debug mode, the compiler preserves the call to WriteSomeDebugInfo because the "DEBUG" preprocessor identifier is applied. In release mode however, the call is removed. This approach is superior to existing C++ preprocessor techniques because it works across compiled assemblies.

Attribute name

Description

System.ObsoleteAttribute

 

A warning or an error will be raised each time this element is used

System.Diagnostics.ConditionalAttribute

 

The compiler will discard any call to the method unless the preprocessor identifier is defined

System.CLSCompliantAttribute

 

Raises an error if the element is not CLS compliant

System.AttributeUsageAttribute

 

Specifies where the attribute can be applied

Table 3: Compile time Attributes supported by Microsoft.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap