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[];

No comments:

Post a Comment

Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...