A great feature of .NET is the ability to mark your code with declarative attributes. These can be used for a variety of purposes, such as how objects should be mapped to database tables, and for marking code to use with framework tools. This approach leverages the benefits of declarative programming and the applications for this are limitless.The demo below is a simple scenario where a custom attribute is created that allows a developer to mark code as not being fully implemented. This could then be used with testing or QA frameworks to analyse the code. In our case we will just scan the class using reflection and prints out a message indicating whether the code is considered fully implemented or not.
The first thing that we must do is to define our attribute:
using System;
using System.Text;
namespace DemoAttribute
{
public class NotFullyImplementedAttribute : Attribute
{
public override string ToString()
{
return "indicate that a member must be implemented.";
}
}
}
Here the ToString() method prints out a message for the NotFullyImplemented status. We can now use this attribute to decorate members of our classes as shown below:
using System;
using System.Text;
namespace DemoAttribute
{
class Employee
{
private string _name;
public Employee()
{
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[NotFullyImplementedAttribute()]
public void PayEmployee()
{
// To Do
}
}
}
In this case we are using our custom attribute to decorate the PayEmployee() method of the Employee class so that we can indicate that this method is not fully implemented. An example of how this attribute can be then interpreted is shown below, where we use reflection to examine the methods of the class Employee.
using System;
using System.Reflection;
using System.Text;
namespace DemoAttribute
{
class MainApp
{
private static bool IsFullyImplemented(MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true))
{
if (attribute is NotFullyImplementedAttribute)
{
Console.WriteLine(attribute.GetType().ToString()+
": This attribute is to "+attribute.ToString ());
return true;
}
}
return false;
}
public static void Main()
{
foreach (MethodInfo method in (typeof(Employee)).GetMethods())
{
if (IsFullyImplemented(method))
{
Console.WriteLine
("Method {0} is not fully implemented.", method.Name);
}
else
{
Console.WriteLine
("Member {0} is implemented!", method.Name);
}
}
Console.Read();
}
}
}
We use the GetMethods() routine to get a collection of the methods in the type Employee. We iterate through this collection and call the IsFullyImpemented function, which tests the attributes of each method (a method can have more than one attribute to see if it is decorate with the NotFullyImplemented attribute.
Download Solution - DemoAttribute.zip