11Aug/090
Custom Attributes
I was asked about Custom Attributes and thought it would make a good blog entry.
Custom Attributes are added to properties of a class. They give extra meaning to these properties.
Here is an example of what they look like and how they are used:
class MyClass
{
[SearchablePropertyAttribute(DisplayType = "Primary")]
public string FirtName
{
get { return firtName; }
set { firtName= value; }
}
[AddressPropertyAttribute(Order = 1, ValidationRequired = true)]
public string Address
{
get { return address; }
set { address= value; }
}
}
SearchablePropertyAttribute and AddressPropertyAttribute are both classes I created. They must extend System.Attribute.
You assign the values to these properties in the class as shown above.
They can be as simple as this:
public class SearchablePropertyAttribute : Attribute
{
public SearchablePropertyAttribute() { }
public string DisplayType = string.Empty;
}
public class AddressPropertyAttribute : Attribute
{
public AddressPropertyAttribute() { }
public int Order = 0;
public bool ValidationRequired = false;
}
To use these attributes, you have to get the PropertyInfo of the object
...
MyClass myclass = new MyClass();
// Get a list of all the properties in the class
PropertyInfo[] piList = typeof(myclass).GetProperties();
// Loop thru each property and check if it is the
foreach (PropertyIfno pi in piList)
{
// Get an array of the AddressPropertyAttribute attributes
AddressPropertyAttribute[] attributes = (AddressPropertyAttribute[])pi.GetCustomAttributes(typeof(AddressPropertyAttribute), true);
// Go thru the attributes and use them as you wish
}
...