5

I wrote custom property attribute and set it on couple of properties in my class. Now I would like during runtime get only properties which has this attribute, be able to get value of the property as well as values of attribute fields. Could You please help me with this task ? thanks for help

leppie
  • 115,091
  • 17
  • 196
  • 297
gruber
  • 28,739
  • 35
  • 124
  • 216
  • I'm fairly sure this is a duplicate, but haven't found a match. I did find the related [Check if property has attribute](http://stackoverflow.com/questions/2051065/check-if-property-has-attribute) and [Finding the attributes on the properties of an instance of a class](http://stackoverflow.com/questions/2999035/finding-the-attributes-on-the-properties-of-an-instance-of-a-class). – C. Ross Jan 19 '11 at 15:45

2 Answers2

15

Here's an example:

void Main()
{
    var myC = new C { Abc = "Hello!" };
    var t = typeof(C);
    foreach (var prop in t.GetProperties())
    {
        var attr = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().FirstOrDefault();
        if (attr != null)
        {
            var attrValue = attr.MaximumLength; // 100
            var propertyValue = prop.GetValue(myC, null); // "Hello!"
        }
    }
}
class C
{
    [StringLength(100)]
    public string Abc {get;set;}
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122
0

You can use PropertyInfo.Attributes

Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183