Tuesday, February 25, 2014

Problems with custom attributes on data members / properties

I created a custom attribute class below:




public class MyCustomAttribute : System.Attribute
{
public string Description
{
get {return _description;}
set {_description = value;}
}

string _description = string.Empty;

/// <summary>
/// Constructor
/// </summary>
/// <param name="description">The description of the property ie: "User Name"</param>
public MyCustomAttribute(string description)
{
_description = description;
}
}

I then applied that to a simple property:



public class MyDataClass
{
[MyCustomAttribute("UserAge")]
public int UserAge;
}

However when I try to get the list of attributes on the data member, the MyCustomAttribute doesn't show up



public main()
{
MyDataClass myDataClass = new MyDataClass();
Attribute[] attrs = Attribute.GetCustomAttributes(myDataClass.UserAge.GetType());

foreach (Attribute attr in attrs)
{
if (attr is MyCustomAttribute)
{
SubComponent sc = attr as MyCustomAttribute;
System.Diagnostics.Debug.WriteLine("UserAge" + sc.Description);

}
}
}







It works GREAT on classes, but for properties it just doesn't seem to hold.

No comments:

Post a Comment