For training related to .net,OOPS,design patterns, MVC,WCF and .net fundamentals
contact at or Click Here

Click here for my training feedbacks


Follow Us

Share your Interview questions here

For software development queries contact

Follow by Email

Learn everything about JSON in a day

06 July 2011

Custom attributes and reflection

In this post, will see
1.Create custom Attributes in c#
2.Attach them to types,
3.Retrieving them at run time

Before starting,What are attributes?
An Attribute is a declarative tag which can be used to provide information to the compiler about the behaviour of the C# elements such as classes and assemblies.

public CustomValue:Attribute
   public string Value{get;set;}
   public CustomValue(string Value)
[CustomValue("Welcome To Programming world")]
public Class MyClass
   Public string MyProperty{get;set;}
//Say myObject is an instance of MyClass
Type ObjPriType=myObject.GetType();
CustomValueAttribute[] CustomAttributes=ObjPriType.GetCustomAttributes(
                typeof(CustomValueAttribute), false) as CustomValueAttribute[];
//CustomAttributes[0].Value is your Value

//In case if attribute is attached to a field in Type Code will be
Type ObjPriType=myObject.GetType();
FieldInfo ObjPriInfo=ObjPriType.GetField("MyProperty");
CustomValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
                typeof(CustomValueAttribute), false) as CustomValueAttribute[];