.NET attributes can be used in different perspectives in
.NET Programming.
- Manage object meta data
- Handle Help information
- And more
When it’s come to the implantation of the .NET attributes,
we have to know three key things,
- How we can declare attributes
- How we can use declared attributes in our implementation
- How we can access them at run time
How we can declare
the custom .NET attributes
.NET attribute itself is a class that we have to implement.
While implementing an Attribute, we have to make sure we do two things,
- Inheriting our attribute class from that Attribute class which is exists under the “System” namespace.
- Specify which types of elements can use the attribute that we are going to implement. This we have to do with AttributeUsage attribute, which is coming with the .NET framework.
Please find an example of attribute implemented,
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;
}
I’m not going to explain things in details of these implementation of this .NET custom Attributes and we know the basics and lets jump into the next step.
How we can use the
declared Attributes
If you are a .NET programmer, surely you have used .NET
attributes already, because we have lots of .NET attributes coming with .NET framework
that we have to deal with day today programming works. Since we have already
implemented an attribute called “HelpAttribute”, unknowingly (maybe) we have
used an attribute, which is coming with .NET framework, called “AttributeUsage”.
Using Attributes is simple; Let’s use the custom attribute
we declared, called “HelpAttribute”,
[HelpAttribute("http://localhost/MyClassInfo")]
class MyClass
{
}
So we used the attribute and provided a value for its
parameter called “url”.
Now it’s time to access the attribute that used in MyClass
class.
How we can access the
attributes
Accessing the attributes at runtime has to be done with .NET
Reflection. Here is a sample code that is used to access the values of
attribute “HelpAttribute”.
class MainClass
{
public static void Main()
{
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i ++)
{
System.Console.WriteLine(attributes[i]);
}
}
}
I didn’t need to go in detail, but just wanted to give an
idea about the .NET attributes, which is a powerful feature coming with .NET
framework.
Please go through this MSDN tutorial for more information,
if you are interested to learn more.
Lakmal
No comments:
Post a Comment