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
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)
        {
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With