Attributes In C#

C# provides a mechanism for defining declarative tags, called attributes, which you can place on certain entities in your source code to specify additional information. The information that attributes contain can be retrieved at run time through reflection. You can use predefined attributes or you can define your own custom attributes.

Every custom attribute class needs 2 things.

1. An AttributeUsage Attribute to declare the class as an attribute. It specifies the language elements to which the attribute can be applied.
2. This class must be derived directly or indirectly from System.Attribute class.

Here is an Example:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple=true)]
public class MyAttribute : Attribute
{
public double _version;
string _name;
public MyAttribute(string name,double ver)
{
this._name = name;
this._version = ver;
}

//This method will retrive the attribute information.
public static void GetMyAttributeInfo(Type t)
{
object[] ClsAttrib =t.GetCustomAttributes(false);
MyAttribute MyAt=(MyAttribute)ClsAttrib[0];
System.Windows.Forms.MessageBox.Show("Name- " + MyAt._name + " , Version" + MyAt._version);
MethodInfo[] TheMethods = t.GetMethods();
for (int i = 0; i < TheMethods.GetLength(0); i++)
{
MethodInfo MethInfo = TheMethods[i];
object[] Attribs = MethInfo.GetCustomAttributes(false);
foreach (Attribute Attrib in Attribs)
{
if (Attrib is MyAttribute)
{
MyAttribute MyAtt = (MyAttribute)Attrib;
System.Windows.Forms.MessageBox.Show("Name- " + MyAtt._name + " , Version" + MyAtt._version);
}
}
}
}

}

[MyAttribute("sanjay",1.0)]
public class TestMyAttribute
{
[MyAttribute("ajay", 1.0)]
public void show()
{
System.Windows.Forms.MessageBox.Show("ajay");
}
}

public static void Main()
{
Base.TestMyAttribute At = new TestMyAttribute();
Base.MyAttribute.GetMyAttributeInfo(typeof(Base.TestMyAttribute));
}

Reference:
http://msdn2.microsoft.com/en-us/library/aa288454(VS.71).aspx
http://www.c-sharpcorner.com/UploadFile/mgold/CreatingnUsingCustomAttributesinCS12032005055442AM/CreatingnUsingCustomAttributesinCS.aspx

No comments: