gruber
gruber

Reputation: 29779

Get all properties with values reflection

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

Upvotes: 5

Views: 19967

Answers (2)

Tim S.
Tim S.

Reputation: 56566

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;}
}

Upvotes: 16

Filip Ekberg
Filip Ekberg

Reputation: 36327

You can use PropertyInfo.Attributes

Upvotes: 0

Related Questions