Search content within the blog

Sunday, May 8, 2011

Defining a custom Attribute in C#

namespace CustomAttributes
{
// create custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class BugFixAttribute : System.Attribute
{
// attribute constructor for positional parameters
public BugFixAttribute
(
int bugID,
string programmer,
string date
)
{
this.BugID = bugID;
this.Programmer = programmer;
this.Date = date;
}
// accessors
public int BugID { get; private set; }
public string Date { get; private set; }
public string Programmer { get; private set; }
// property for named parameter
public string Comment { get; set; }
}
// ********* assign the attributes to the class ********
[BugFixAttribute(121, "Jesse Liberty", "01/03/08")]
[BugFixAttribute(107, "Jesse Liberty", "01/04/08",
Comment = "Fixed off by one errors")]
public class MyMath
{
public double DoFunc1(double param1)
{
return param1 + DoFunc2(param1);
}
public double DoFunc2(double param1)
{
return param1 / 3;
}
}
public class Tester
{
static void Main(string[] args)
{
MyMath mm = new MyMath( );
Console.WriteLine("Calling DoFunc(7). Result: {0}",
mm.DoFunc1(7));
}
}
}
Output:
Calling DoFunc(7). Result: 9.3333333333333333

No comments:

Post a Comment