C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Using Multiple Custom Attributes with a Class


Posted Date: 04 Jul 2005    Resource Type: Articles    Category: .NET Framework
Author: Balamurali BalajiMember Level: Diamond    
Rating: 1 out of 5Points: 10



Introduction



Needless to say, attributes provide a powerful method of associating declarative information in your program elements. Custom Attributes are classes that derive from System.Attribute. Once associated with a program entity, the attribute can be queried at run time using a technique called Reflection. Class, Interface, Property, Event, Method are few of the program entities you typically put in your code. You can associate more than one custom attribute to your program element. This would provide you an effective way of adding metadata to your type and retrieve metadata information during runtime.

Creating Custom Attribute



To create a custom attribute, you need to associate the class with the intrinsic attribute AtributeUsage attribute. The class should be derived from System.Attribute.

AttributeUsage attribute describes the behavior and capabilities of your custom attribute.

Following is the syntax for defining the AttributeUsage attribute:



[AttributeUsage(AttributeTarget,AllowMultiple=true/false,Inherited=inherited)]



AttributeTargets specifies the kind of element on which it is valid to apply an attribute. You can set the attribute applicable to all of the elements also.
AllowMultiple is a Boolean value that indicates whether multiple attributes can be specified for the program element. The default value for this parameter is False.


// This class defines the custom attribute Hardware
[AttributeUsage(AttributeTargets.Class)]
public class HardWare : System.Attribute
{
public string ID;
public string Name;
public string Manufacturer;

public HardWare(string ID)
{
this.ID = ID;
this.name = "Monitor";
this.manufacturer = "IBM";
}
}




The above code defines a custom attribute "Hardware" and holds three data, Id, Name and Manufacturer. The constructor has one positional parameter, ID. AttributeTargets is set to Class. There are other possible target values: Assembly, Class, Constructor, Delegate, Event, Field, Interface, Method, Module, Property, Struct etc.,



// This class defines the custom attribute Model
[AttributeUsage(AttributeTargets.Class)]
public class Model : System.Attribute
{
public int width;
public int length;
public string colour;

public Model(int width, int length, string colour) // positional parameter
{
this.width = width;
this.length = length;
this.colour = colour;
}
}



The above code defines a custom attribute "Model" and holds another set of data length, height and Color. The constructor of this class take all the three parameters as positional parameters.



// This class uses the custom attributes Hardware and Model


[HardWare("12345")]
[Model(23,18,"Red")]
class monitor
{
public static void Main()
{
Attribute[] a = Attribute.GetCustomAttributes(typeof(monitor));

foreach(Attribute attr in a)
{
if(attr is HardWare)
{
HardWare h1 = (HardWare)attr;
Console.WriteLine("ID:" + h1.ID);
Console.WriteLine("Name:" + h1.Name);
Console.WriteLine("Manufacturer:" + h1.Manufacturer);
}
if(attr is Model)
{
Model m1 = (Model)attr;
Console.WriteLine("width:" + m1.width);
Console.WriteLine("length:" + m1.length);
Console.WriteLine("color:" + m1.colour);
}
}

}



Now, look at the class "monitor". It is linked to both the custom attributes "Hardware" and "Model". Once this is done, you can use the GetCustomAttributes() method to re-collect all the custom attributes during runtime. It returns the array of attribute objects, and hence you need to typecast each of the elements in the array to the respective custom attribute type.




Attribute b =Attribute.GetCustomAttribute(typeof(monitor),typeof(HardWare));
HardWare h2 = (HardWare)b;
Console.WriteLine ( h2.ID + " " + h2.name + " " + h2.manufacture);

Attribute b1 = Attribute.GetCustomAttribute(typeof(monitor),typeof(Model));
Model m2 = (Model)b1;
Console.WriteLine ( m2.width.ToString() + " " + m2.length.ToString() + " " + m2.colour);



The above piece of code uses the GetCustomAttribute() method that returns you the specified attribute in a type. Since it deals with the single attribute, you need to supply the names of both the Type and Custom Attribute.



System.Reflection.MemberInfo info = typeof(monitor);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i ++)
{
System.Console.WriteLine(attributes[i]);
}


The above code example shows the simplest way of using reflection to get access to custom attributes. The System.Reflection.MemberInfo class has a GetCustomAttributes family of methods to query information about custom attributes.

Summary



Custom attributes are not just useful in providing custom information to our program elements, they serve as a way to explore further into retrieve metadata information on our types, methods etc using Reflection.




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Don't waste time! Synchronize your ThreadPool.
Previous Resource: Understanding the process of Garbage Collection in .net framework - Step by Step
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use