RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


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.

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.

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 ()
[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.

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 ()
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




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



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



Raises an error if the element is not CLS compliant



Specifies where the attribute can be applied

Table 3: Compile time Attributes supported by Microsoft.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date