In this series we will be learning about the Attribute Oriented Programming .
How it can help us write simpler and beautifull code .
All of us would have used attributes as some point of time . In WCF we use a lot
of attributes . In MEF everything is done using attributes .In General most of
the time we use attributes provided to us by .NET but in this series we will
try to learn about how to create Custom attributes and where in real world
scenarios we could use them .
In this article we would learn about the simple use of Attribute Oriented
Programming.
As the name suggests Attribute Oriented Programming is all about using
Attributes the right way .
Attributes provide a powerful method of associating metadata, or declarative
information, with code (assemblies, types, methods, properties, and so forth).
After an attribute is associated with a program entity, the attribute can be
queried at run time by using a technique called reflection.
[From MSDN]
So lets get started with a simple example. I Have created a simple attribute as
shown below:
Before we take up a example. Let's see how what we need to do to create a Custom
Attribute.
Creating a Custom Attribute :
We would create a class which would extend from System.Attribute.
A sample class would look like below:
[AttributeUsage(AttributeTargets.All,
AllowMultiple = false)]
public sealed
class FixMeAttribute
: System.Attribute
{
public string
Value { get; set;
}
public FixMeAttribute() {}
public FixMeAttribute(string
value) {
Value = value;
}
}
Check out the AttributeUsage Attribute on top of the FixMeAttribute class .We
will discuss about this in detail in a next article .The class is made sealed
as I do not want anyone to extend the functionality of this class.
Lets see how can I use this attribute .
[FixMe("Incorporate
4.0 features")]
class MyClass
{
}
Was Simple enough. Just place FixMe which becomes our Attribute Name on top of
the Class.
Now lets see if our Attribute does something usefull for us.
A bit of Reflection is used to get the Class Name Type. The advantage of
Attributes is we can easily access the attribute using Reflection.
class
CustomAttributeTest
{
public static
void Main()
{
Type clazz =
typeof(MyClass);
Object[] atts =
clazz.GetCustomAttributes(typeof(FixMeAttribute),
false);
foreach (FixMeAttribute
att in atts)
{
System.Console.WriteLine("You
should fix '" + clazz.FullName + "' : "
+ att.Value);
}
Console.ReadKey();
}
}
That's all it is there to our First attribute Lets give it a quick run.
Cool. In next article I would explain some of the features we used here. Till
then, Happy Coding.
References:
1.
http://hornad.fei.tuke.sk/~poruban/atop/