Pages

Men

rh

6/16/2012

Attributes in C#

Attributes:
  • An attribute is a piece of additional declarative information that is specified for a declaration.
  • Attributes are a new kind of declarative information.
  • We can use attributes to define both design-level information (such as help file, URL for documentation) and run-time information (such as associating XML field with class field).
  • We can also create "self-describing" components using attributes.
 Types of Attributes:
  • Predefined Attribute
  • Custom Attribute 
 Predefined Attributes:
 
There is a small set of pre-defined attributes present in C#.
 
Example:
 
using System;
public class AnyClass 
{
    [Obsolete("Don't use Old method, use New method", true)]
    static void Old( ) { }
   
    static void New( ) { }
   
    public static void Main( ) 
    {
        Old( );
    }
}
 
 
In this example we use attribute Obsolete, which marks a program entity that should not be used. The first parameter is the string, which explain why the item is obsolete and what to use instead of this. In fact you can write any other text here. The second parameter tells the compiler to treat the use of the item as an error. Default value is false, which means compiler generates a warning for this. 

When we try to compile above program, we will get an error:
AnyClass.Old ()' is obsolete: 'Don't use Old method, use new method'
 
Custom Attribute:
 
Derive our attribute class from System.Attribute class as stated in C# language specification (A class that derives from the abstract class System.Attribute, whether directly or indirectly, is an attribute class. The declaration of an attribute class defines a new kind of attribute that can be placed on a declaration) and we are done.
 
EXAMPLE:
 
using System;
public class HelpAttribute : Attribute
{
}
 
Believe me or not we have just created a custom attribute. We can decorate our class with it as we did with obsolete attribute.
 
[Help()]
public class AnyClass
{
}
 
Note: it is a convention to use the word Attribute as a suffix in attribute class names. However, when we attach the attribute to a program entity, we are free not to include the Attribute suffix. The compiler first searches the attribute in System.Attribute derived classes. If no class is found, the compiler will add the word Attribute to the specified attribute name and search for it. 

But this attribute does nothing useful so far. To make it little useful let add something more in it.
Example
 
using System;
public class HelpAttribute : Attribute
{
    public HelpAttribute(String Descrition_in)
    {
        this.description = Description_in;
    }
    protected String description;
    public String Description 
    {
        get 
        {
            return this.description;
                 
        }            
    }    
}
[Help("this is a do-nothing class")]
public class AnyClass
{
}

No comments :

Post a Comment