using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Csharp
{
//DEFINING CUSTOM ATTRIBUTE
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Method|
AttributeTargets.Field|
AttributeTargets.Property|
AttributeTargets.Constructor , AllowMultiple =true)]
//CONSTRUCTING AND NAMING NEW CUSTOM ATTRIBUTE
public class ClassAttributes : System.Attribute
{
//POSITIONAL PARAMETERS-specify essential information about attributes
private int sno;
private string msg;
//MUST HAVE ATLEAST ONE CONSTRUCTOR.
//constructor of ClassAttribute Class for positional parameters
public ClassAttributes(int s, string m)
{
this.sno=s;
this.msg=m;
}
public int getSno
{
get{ return sno;}
}
public string getMsg
{
get { return msg; }
}
}
//CLASS LEVEL attribute set----APPLYING
[ClassAttributes(1,"Amrit Setting Class Level Attributes")]
[ClassAttributes(2, "i am Attribute of class -> AttributeExample")]
class AttributeExample
{
//METHOD LEVEL attribute set---APPLYING
[ClassAttributes(3, "I am Attribute of method DisplayClassMetaData()")]
//display metadeta using reflecftion
public void DisplayClassMetaData()
{
Type type = typeof(AttributeExample);
//display "Class LEVEL" attributes...
Console.WriteLine("\nCLASS LEVEL ATTRIBUTES");
foreach (Object a in type.GetCustomAttributes(typeof(ClassAttributes), false))
{ // create object
ClassAttributes obj = (ClassAttributes)a;
if (null != obj)
{
Console.WriteLine("\nSNo={0} \n Message={1}\n", obj.getSno, obj.getMsg);
}
}
}
//again METHOD LEVEL attribute set---APPLYING
[ClassAttributes(4, "I am Attribute of method DisplayMethodMetaData ()")]
public void DisplayMethodMetaData()
{
Type type = typeof(AttributeExample);
//display "Method LEVEL attributes....
Console.WriteLine("\nMETHOD LEVEL ATTRIBUTES");
foreach (MethodInfo method in type.GetMethods())
{ foreach(Attribute a in method.GetCustomAttributes(true))
{
try
{
ClassAttributes obj = (ClassAttributes)a;
if (null != obj)
{
Console.WriteLine("\nSNo={0} \n Message={1}\n", obj.getSno, obj.getMsg);
}
}
catch (Exception e)
{
}
finally
{
Console.WriteLine("***********");
}
}
}
}
public static void Main()
{
AttributeExample o = new AttributeExample();
o.DisplayClassMetaData();
Console.ReadLine();
o.DisplayMethodMetaData();
Console.ReadLine();
}
}
}