Saturday 7 May 2011

Need of Attributes in C#

Attributes
Attributes contains a powerful method of associating declarative information with C# code for types, methods, properties. Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
Uses of Attributes:

* Associating help documentation with program entities (through a Help attribute).
* Associating value editors to a specific type in a GUI framework (through a Value Editor attribute).
 

using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute 
{
   public readonly string Url;

   public string Topic               // Topic is a named parameter
   {
      get 
      { 
         return topic; 
      }
      set 
      { 

        topic = value; 
      }
   }

   public HelpAttribute(string url)  // url is a positional parameter
   {
      this.Url = url;
   }

   private string topic;
}
When do we need attributes ?
1.The System.ObsoleteAttribute attribute that we have just described is a good example of how an attribute is used by the compiler, certain standard attributes which are only destined for the compiler are not stored in the assembly.
2.An attribute can be consumed by the CLR during execution. For example the .NET Framework offers the System.ThreadStaticAttribute attribute. When a static field is marked with this attribute the CLR makes sure that during the execution, there is only one version of this field per thread.
3.An attribute can be consumed by a debugger during execution. Hence, the System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the display of an element of the code the state of an object for example) during debugging.

No comments:

Post a Comment