Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Custom Attributes from Properties

so I have a collection of Properties from my class which I want to loop through. For each property I may have custom attributes so I want to loop through those. In this particular case I have a custom attribute on my City Class as such

public class City
{   
    [ColumnName("OtroID")]
    public int CityID { get; set; }
    [Required(ErrorMessage = "Please Specify a City Name")]
    public string CityName { get; set; }
}

The attribute is defined as such

[AttributeUsage(AttributeTargets.All)]
public class ColumnName : System.Attribute
{
    public readonly string ColumnMapName;
    public ColumnName(string _ColumnName)
    {
        this.ColumnMapName= _ColumnName;
    }
}

When I try to loop through the properties [which works fine] and then loop through the attributes it just ignores the for loop for the attribute and returns nothing.

foreach (PropertyInfo Property in PropCollection)
//Loop through the collection of properties
//This is important as this is how we match columns and Properties
{
    System.Attribute[] attrs = 
        System.Attribute.GetCustomAttributes(typeof(T));
    foreach (System.Attribute attr in attrs)
    {
        if (attr is ColumnName)
        {
            ColumnName a = (ColumnName)attr;
            var x = string.Format("{1} Maps to {0}", 
                Property.Name, a.ColumnMapName);
        }
    }
}

When I go to the immediate window for the property that has a custom attribute I can do

?Property.GetCustomAttributes(true)[0]

It will return ColumnMapName: "OtroID"

I can't seem to fit this to work programmatically though

like image 424
Jordan Avatar asked Jan 20 '12 22:01

Jordan


1 Answers

You want to do this I believe:

PropertyInfo[] propCollection = type.GetProperties();
foreach (PropertyInfo property in propCollection)
{
    foreach (var attribute in property.GetCustomAttributes(true))
    {
        if (attribute is ColumnName)
        {
        }
    }
}
like image 94
mservidio Avatar answered Sep 20 '22 02:09

mservidio