Original source: http://www.codeguru.com/csharp/csharp/cs_syntax/ttributes/Article.php/c5831/
Using Attributes In C # rating: None
SADAF Alvi (View Profile) September 24, 2002
ENVIRONMENT: C #
Introduction
Attributes are a new kind of declarative information. We can use attributes to define both design-level information (such as a help file or a URL for documentation) and run-time information (such as associating an xml field with a class field). We also can create "self-describing" components using attributes. in this tutorial, we will see how we can create and attach attributes to various program entities, and how we can retrieve attribute information in a run-time environment.
Definition
(Continued)
As stated in msdn (ms-help: //ms.msdnqtr.2002apr.1033/csspec/html/vclrfcsharpspec_17_2.htm):
"An attribute is a piece of additional declarative information". "
Using pre-defined Attributes
There Is A Small Set of Pre-Defined Attributes Present In C #. Before Learning How To create Our OWN Custom Attributes, We Will First Look Atho...
Using system;
Public class anyclass
{
[Obsolete ("Don't Use Old Method, Use New Method", True]
Static void old ()
{
}
Static void new ()
{
}
Public static void main ()
{
OLD ();
}
}
Take a look at the this example. We use the attribute Obsolete, which marks a program entity that should not be used. The first parameter is the string, which explains why the item is obsolete and what to use instead. In fact, you can write any other text here. The second parameter tells the compiler to treat the use of the item as an error. The default value is false, which means the compiler generates a warning for this.When we try to compile the preceding program, we will Get an error:
Anyclass.old () 'is obsolete:' don't use old method, use new method '
Developing Custom Attributes
Now We will see how we can develop our own attributes. Here is a small recipe to create ur ion attributes.
Derive our attribute class from the System.Attribute class as stated in the C # language specification (A class that derives from the abstract class System.Attribute, whether directly or indirectly, is an attribute class. The declaration of an attribute class defines a new kind Of attribute That CAN Be Placed on a Declaration) and we are done.
Using system;
Public Class Helpattribute: Attribute
{
}
Believe Me or Not, We Have Just Created A Custom Attribute. We can Decorate Our class with it as we did with an off.
[Help ()] public class anyclass
{
}
Note: It is a convention to use the word Attribute as a suffix in attribute class names However, when we attach the attribute to a program entity, we are free not to include the Attribute suffix The compiler first searches the attribute in System... Attribute Derived Classes. If No Class Is Found, The Compiler Will Add The Word Attribute To The Specified Attribute Name and Search for IT.
But this attribute does Nothing useful so far. To make it it a little more useful, let's address more in it.using system;
Public Class Helpattribute: Attribute
{
Public Helpattribute (String Description_IN)
{
THIS.DESCRIPTION = Description_IN;
}
PROTECTED STRING DESCRIPTION; Public String Description
{
Get {
Return this.description;
}
}
}
[Help ("this is a do-nothing class"]
Public class anyclass
{
}
In Above Example, We Have Added a Property To Our Attribute Class. We will query it at runtime in the last section.
Defining OR Controlling The Usage of Our Attribute
AttributeUsage class is another pre-defined class that will help us control the usage of our custom attributes. That is, we can define attributes of our own attribute class. It describes how a custom attribute class can be used.
Attributeusage Has Three Properties That We Custom Attribute. These Three Properties Are Discussed in The Following Sections.
Validon
Through this property, we can define the program entities on which our custom attribute can be placed. The set of all possible program entities on which an attribute can be placed is listed in the AttributeTargets enumerator. We can combine several AttributeTargets values by using a bitwise Or Operation.
Allowmultiple
This Property Marks WHether Our Custom Attribute Can Be Placed More Than On The Same Program Entity.
Inherited
We can control the inheritance rules of outtribute by using this property. This property marks WHether Our Attribute Will be inherited by the class deact from the class on Which We Have Placesd IT.
Let's do something the attributeusage attribute on our owlp attribute and control the usage of ing it.using system;
[AttributeUSAGE (AttributeTargets.class), unlowmultiple = false, inherited = false]
Public Class Helpattribute: Attribute
{
Public Helpattribute (String Description_IN)
{
THIS.DESCRIPTION = Description_IN;
}
Protected string description;
Public String Description
{
Get {
Return this.description;
}
}
}
First, Look at The AttributeTargets.class. It States That The Help Attribute Can Be Placed ON A Class ONLY WILL RESULT IN An Error:
Anyclass.cs: attribute 'help' is not valid on this deflaration type. It is valid on 'Class' Declarations Only.
Now try to put it in a method:
[Help ("this is a do-nothing class"]
Public class anyclass
{
[Help ("this is a do-nothing method"] // error
Public void Anymethod ()
{
}
}
We can use AttributeTargets.All to allow the Help attribute to be placed on any program entity (Possible values are: Assembly, Module, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, Delegate, All = Assembly | Module | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate, ClassMembers = Class | Struct | Enum | Constructor | Method | Property | Field | Event | Delegate | Interface).
Now consider allowmultiple = false. This States That An Attribute Cannot Be Placed Multiple Times.
[Help ("this is a do-nothing class"]
[Help ("IT Contains A Do-Nothing Method")]]
Public class anyclass
{
[Help ("this is a do-nothing method")] // errorpublic void Anymethod ()
{
}
}
IT generates a compile-time error.
Anyclass.cs: duplicate 'Help' Attribute
Okay, now let's discuss the last property. Inherited indicates whether the attribute, when placed on a base class, is also inherited by classes that derive from that base class. If Inherited for an attribute class is true, that attribute is inherited. However, If inherited for an attribute class is false or it is unspecified, there is attribute is not inherited.
Let's support..
[Help ("Baseclass")] public class base {} public class derive: base {}
We Have Four Possible Combinations:
[AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = false] [AttributeUsage (AttributeTargets.Class, AllowMultiple = true, Inherited = false] [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true] [AttributeUsage (AttributeTargets. Class, allowmultiple = true, inherited = true]
Thase Combinations Are Discussed in The Following Sections.
First Case
IF We query (We Well See Later How To Query The Attributes of a class at run-time) The Derive Class for ITS Help Attribute, We will not find it because the inherited attribute is set to false.
SECOND CASE
The Second Case Is Not Different; An Inherited Attribute Is Set To False In This Case, Also.
Third Case
To Explain The Third and Fourth Cases, Let's Add The Same Attribute To The Derive Class, Also.
[Help ("Baseclass")]
Public Class Base
{
}
[Help ("DeriveClass")]]]
Public Class Derive: Base
{
}
Now, if we query about the Help attribute, we will get the drive class attribute only because inherited is true, but multiples are not allowed so the base class Help is overridden by the Derive class Help attribute.Fourth Case
In The Fourth Case, We Well Get Both Attributes WHEN We query Our Derive Class for The Help Attribute Both Inheritance and Multiples Are ALOWED IN this case.
Note: The Attributeusage Attribute Is Only Valid On Classes Derived from System.attribute and Both Allowmultiple and Inherited Are False for this Attribute.
Positional Versus Named Parameters
Positional parameters are parameters of the attribute's constructor. They are mandatory and a value must be passed every time the attribute is placed on any program entity. On the other hand, Named parameters are actually optional and are not parameters of the attribute's constructor.
To Explain It in More Detail, Let's Add Another Property to Our Help Class.
[AttributeUSAGE (AttributeTargets.class, AllowMultiple = false, inherited = false)]
Public Class Helpattribute: Attribute
{
Public Helpattribute (String Description_IN)
{
THIS.DESCRIPTION = Description_IN;
THIS.Version = "no version is defined for this clas";
}
Protected string description;
Public String Description
{
Get {
Return this.description;
}
}
Protected string version;
Public String Version
{
Get {
Return this.version;
}
// if We Ever Want Our Attribute User To set this property,
// WE MUST Specify Set Method for IT
SET {
THIS.VERSION = VALUE;
}
}
}
[Help ("this is class1")]]]
Public Class Class1
{
}
[Help ("this is class2", version = "1.0")]
Public class clas2
{
}
[Help ("this is class3", version = "2.0", description = "this is do-nothing class"] public class class3
{
}
WHEN We query class1 for the Help Attribute and ITS Properties, We Will Get:
Help.description: this is class1
Help.Version: No Version is defined for this class
Because we did not define any value for the Version property, the value set in the constructor is used. If no value is defined, the default value of the type is used (for example, in case int, the default value is zero) .
Now, Querying Class2 Will Result In the Following:
Help.description: this is class2
Help.Version: 1.0
Do not use multiple constructors for optional parameters. Instead, mark them as named parameters. We called them named because, when we supply their value in the constructor, we have to name them. For example, in second class, we define Help.
[Help ("this is class2", version = "1.0")]
In The Attributeusage Example, The Validon Parameter Is A Positional Parameter and Inherited and Allowmultiple Are Named Parameters.
Note: To set the value of named parameter in the constructor of the attribute, we must supply the set method for that property; otherwise, it will generate a compile-time error, such as the following message:
'Version': Named Attribute Argument Can't Be a Read-Only Property
Now what happens when we query class3 for the help attribute and it 's the Same Compile-Time Error.
'Description': named attribute argument can't be a ready - Only Property
Now Modify The Help Class and Add The Set Method of Description. Now The Output Will BE:
Help.description: this is do-nothing class help.version: 2.0
What happens behind the scenes is first the constructor is called with positional parameters, and then the set method is called for each named parameter. The value set in the constructor is overriden by the set method.Parameter Types
The Types of Parameters for An Attribute Class Are Limited to The Following:
bool, byte, char, double, float, int, long, short, string System. Type object An enum type, provided that it and any types in which it is nested are publicly accessible A one-dimensional array involving any of the types listed ABOVE
Attribute IdentifierS
Let's suppose that we want to place the Help attribute on the entire assembly The first question arises:. Where should we place that Help attribute so that the compiler can determine that it is placed on an entire assembly ?? Consider another situation: We want to Place An Attribute on The Return Type of a Method. How WELD THE Compiler Determine That We Are Places It ON A Method-Return-Type and Not on An entire method
To Resolve Such Ambiguities, We Use An Attribute Identifier. With The Help of Attribute Identifiers, We CAN Explicitly State The Entity On Which We Are Placing The Attribute.
For example:
[assmbly: Help ("this a do-nothing assembly"]]]]
THE Assembly Identifier Tells The Compiler That this attribute is attached to the entire assembly. The Possible Identifiers Are:
Assembly Module Type Method Property Event Field Param Return
Querying Attributes At Run Time
WE HAVE Seen How To create attributes and how to attach the. Now it's time to learn how the user of our class can query this information at run time.
To query a program entity about its attached attributes, we must use reflection. Reflection is the ability to discover type information at run time.We can use the .NET Framework Reflection APIs to iterate through the metadata for an entire assembly and produce a list of All classes, Types, And Methods That Have Been Defined for That Assembly.
REMEMBER THE OLD HELP Attribute and The Anyclass Class?
Using system;
Using system.reflection;
Using system.diagnostics;
// attaching help attribute to entire assembly
[Assembly: Help ("This assembly and their run-time query.")]]]]
// ur custom attribute class
Public Class Helpattribute: Attribute
{
Public Helpattribute (String Description_IN)
{
// Todo: add constructor logic here
THIS.DESCRIPTION = Description_IN;
}
Protected string description;
Public String Description
{
get
{
Return this.description;
}
}
}
// attaching the help attribute to our anyclass
[Helpstring ("this is a do-nothing class.")]]
Public class anyclass
{
// attaching the help attribute to our anymethod
[Help ("this is a do-nothing method.")]]]
Public void Anymethod ()
{}
// attaching help attribute to our Anyint Field
[Help ("this is any integer.")]]]
Public int Anyint;
}
Class queryApp
{
Public static void main ()
{}
}
We will add the attribute-query code to our main method in the next two sections.
Querying assembly attributes
In the following code, we get the current process name and load the assembly using the LoadFrom method of the Assembly class. Then, we use the GetCustomAttributes method to get all the custom attributes attached to the current assembly. Next, for each statement iterate through all the attributes and try to cast each attribute as a Help attribute (casting objects using the as keyword has an advantage that if the cast is invalid, we do not have to worry about an exception being thrown. What will happen instead is that the Result Will Be Null). The next line checks WHETER THE CAST IS VALID AND NOT Equal to Null; The it Displays the helpproperty of the attribute.class queryApp
{
Public static void main ()
{
Helpattribute helpattr;
// querying assembly attributes
String assemblyname; process
P = process.getcurrentprocess ();
askMBLYNAME = P.ProcessName ".exe";
AskEMBLY A = askMBLY.LOADFROM (AssemblyName);
Foreach (Attribute Attr In A.getCustomattributes (TRUE))
{
Helpattr = attr as helpattribute;
IF (NULL! = Helpattr)
{
Console.writeline ("Description of {0}: / n {1}", assemblyname, helpattr.description;
}
}
}
}
The Output of The Following Program IS:
Description of queryattribute.exe: this assembly demonstrates Custom Attributes Creation and Their Run-Time Query.
Press any key to pay.
Querying Class, Method, And Field Attributes
In The Following Code, The Only Unfamiliar Item Is The First Line in The Main Method.
TYPE TYPE = TypeOf (AnyClass);
It gets the Type object associated with our AnyClass class using the typeof operator. The rest of the code for querying class attributes is similar to the preceding example and does not need any explanation (I think) .For querying a method's and field's attributes, WE First Get All the Methods And Fields Present in The Class; THEN We query Their Associated Attributes in The Same Manner As We Did Class Attributes
Class queryApp {
Public static void main ()
{
TYPE TYPE = TypeOf (AnyClass);
Helpattribute helpattr;
// Querying Class Attributes
Foreach (Attribute Attr In Type.Getcustomattributes (TRUE))
{
Helpattr = attr as helpattribute;
IF (NULL! = Helpattr)
{
Console.writeline ("Description of anyclass: / n {0}", helpattr.description;
}
}
// Querying Class-Method Attributes
FOREACH (MethodInfo method in type.getMethods ())
{
Foreach (Attribute Attrin Method.getCustomattributes (TRUE))
{
Helpattr = attr as helpattribute;
IF (NULL! = Helpattr)
{
Console.writeline ("Description of {0}: / n {1}", method.name, helpattr.description;
}
}
}
// querying class-field (only public) Attributes
FOREACH (FieldInfo Field in Type.Getfields ())
{
Abtribute Attr In Field.getCustomattributes (TRUE))
{
Helpattr = attr as helpattribute;
IF (NULL! = Helpattr)
{
Console.writeline ("Description of {0}: / n {1}", field.name, helpattr.description;
}
}
}
}
}
The Output of The Following Program IS:
Description of anyclass: this is a do-nothing class.
Description of anymethod: this is a do-nothing method.
Description of anyint: this is any integer.
Press any key to continche