C# .Net Tutorial Attributes

Started by sukishan, Jul 11, 2009, 02:41 PM

Previous topic - Next topic

sukishan

C# .Net Tutorial Attributes

This article deals with the new C# .net features named attributes. This can be used as a Self paced C# .net training or C# tutorial material.

   C# .net Attributes provide a powerful method of associating declarative information with C# code. It can work with types, methods, properties and other language components.

   As a thumb-rule, a class is said to be an attribute class, if it directly or indirectly derives from the System.Attribute class.




Attributes in C# .net - Sample:
   This C# tutorial on attributes uses custom attributes by defining an attribute class. The class ProductInfo is derived from System.Attribute class. This class contains information about application author and product version. The created class is:


--------------------------------------------------------------------------------

[AttributeUsage(AttributeTargets.All)]
public class ProductInfo : System.Attribute
{

public ProductInfo(double version,string name)
{

m_version = version;
m_authorName = name;

}

public double Version
{

get { return m_version; }

}

private double m_version = 1.00;
public string AuthorName
{

get { return m_authorName; }

}

private string m_authorName;

}


--------------------------------------------------------------------------------
There is a new item in the first line of code. It is an attribute that allows us to use a c# attribute keyword AttributeUsage to all elements of our class (parameter AttributeTargets.All).
   Now we can use these c# attributes in declaration of any other custom class:

[ProductInfo(1.005,"CoderSource"])

public class AnyClass { }

   After creating simple custom type c# attributes, we can get information about all its attributes at runtime. Such run-time information can be pulled out from a class by using the namespace System.Reflection. In main function of our C# tutorial program we can get from our object all information about custom attributes. Next piece of code demonstrate it:


--------------------------------------------------------------------------------

MemberInfo membInfo;
membInfo = typeof(AnyClass);
object [] attributes;
attributes = membInfo.GetCustomAttributes(typeof(ProductInfo),true);

if(attributes.GetLength(0)!=0)
{

ProductInfo pr = (ProductInfo) attributes[0];
Console.WriteLine("Product author: {0}",pr.AuthorName);
Console.WriteLine("Product version; {0}",pr.Version);

}
A good beginning makes a good ending