Using Attributes in C#


How to use

Copy the code in a text editor and save it as a .cs file and compile it using "csc <filename>".

Description

This article shows how to create custom attribute classes, use them in code, and query them.

Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.

We can create a custom attribute by defining an attribute class, a class that derives directly or indirectly from System.Attribute.

The below given code shows how to declare and use an attribute. This code returns the name of the author and the version of the type to which the attribute is assigned.

Note:  AttributeUsage specifies the language elements to which the attribute can be applied
GetCustomAttributes returns an array of objects that are the run-time equivalents of the source code attributes.

Source Code:

using System;
namespace Attributes
{
class Class1
{
[AttributeUsage(AttributeTargets.All)]
public class Details : Attribute
{
public readonly string MemberName;
public double Version = 1.0;
public Details(string name)
{
this.MemberName = name;
}
public double version
{
get
{
return Version;
}
set
{
Version =
value;
}
}
}
[Details("Rajadurai")]
public interface Iattribute
{
void display();
}
[Details("Sankar")]
public class classAttribute1 : Iattribute
{
public void display()
{
Console.WriteLine("My Author is Sankar");
}
}
static void Main(string[] args)
{
processAttributes p =
new
processAttributes(typeof(classAttribute1));
processAttributes q =
new
processAttributes(typeof(Iattribute));
//processAttributes r = new
processAttributes(typeof(methodAttribute1));
int i = Console.Read();
}
public class processAttributes
{
public processAttributes(Type t)
{
Attribute[] attrs =Attribute.GetCustomAttributes(t);
foreach(Attribute attr in attrs)
{
if (attr is Details)
{
Console.WriteLine("Type Name :{0}",t);
Details d = (Details)attr;
Console.WriteLine("Author Name :{0}",d.MemberName);
Console.WriteLine("Version :{0}",d.version);
Console.WriteLine("");
}
}
}
}
}
}