Tuesday, November 25, 2008

Create Custom Attribute in .net

/* class to create custom attribute .The custom attribute class must be inherited from Attribute which is an abstract class
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.All,Inherited=true,AllowMultiple=true)]
class AuthorAttribute:Attribute
{
private string authorFirstName = string.Empty;
private string authorLasttName = string.Empty;
private string authorCreationDate = string.Empty;
public AuthorAttribute(string firstName, string lastName)
{
this.authorFirstName = firstName;
this.authorLasttName = lastName;
}
public AuthorAttribute(string firstName, string lastName,string creationDate)
{
this.authorFirstName = firstName;
this.authorLasttName = lastName;
this.authorCreationDate = creationDate;
}
public string AuthorName
{
get
{
return (this.authorFirstName + " " + authorLasttName);
}
}

public string CreationDate
{
get
{
return (this.authorCreationDate);
}
}

}
}

//Implement Custom Attribute

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
[Author("Nitendra Singh","raghuwanshi","25/11/2008")]
class Program
{
static void Main(string[] args)
{
Program pr = new Program();
DisplayAttributes(pr.GetType());
Console.ReadLine();
}
static void DisplayAttributes(Type type)
{
AuthorAttribute author = null;
foreach (object objAttribute in type.GetCustomAttributes(false))
{
author = objAttribute as AuthorAttribute;
if (author == null)
continue;
Console.WriteLine("Name :" + author.AuthorName);
Console.WriteLine("Date :" + author.CreationDate);
}
}
}
}

No comments: